我应该更改此代码中的哪些内容以使其打印某些内容?插入函数是否需要为struct类型才能插入节点



老实说,我真的不明白这段代码是如何工作的。为了让它发挥作用,我只需要改变一些函数的类型,还是需要改变更多?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct LinkedList{
int data;
struct LinkedList* next;
};
int main(){
struct LinkedList *A = NULL;
insert(A, 3);
printList(A);
return 0;
}
void insert(struct LinkedList *root, int item){
root=malloc(sizeof(struct LinkedList));
root->data= item;
root->next = NULL;
}
void printList(struct LinkedList *head){
struct LinkedList *temp=head;
while (temp != NULL){
printf("%d", temp->data);
temp = temp->next;
}
}

有必要将其作为参数传递给"插入";函数是指向";struct LinkedList"指针。。。而不是";struct LinkedList"指针本身。

此外,您只是在呼叫";insert((";一旦在这个版本中,所以你看不到和你的";insert((";没有创建链接列表。相反,它正在重写";头部;(您的"A"指针(。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct LinkedList{
int data;
struct LinkedList* next;
};
/* prototypes */
void insert(struct LinkedList **root, int item);
void printList(struct LinkedList *head);
int main(){
struct LinkedList *A = NULL;
insert(&A, 3);
insert(&A, 4);
printList(A);
return 0;
}
void insert(struct LinkedList **root, int item){
struct LinkedList *newptr;
newptr=malloc(sizeof(struct LinkedList));
newptr->data= item;
// ORIGINAL: root->next = NULL;
newptr->next = *root;
*root = newptr;
}
void printList(struct LinkedList *head){
struct LinkedList *temp=head;
while (temp != NULL){
printf("%dn", temp->data);
temp = temp->next;
}
}

最新更新