[英]What should I change in this code to make it print something? Does the insert function need to be of type struct to insert a node?
I honestly don't really understand how this code works.老实说,我真的不明白这段代码是如何工作的。 To make it work would I just need to change the type of some of the functions or would I need to change more than that?为了使其工作,我只需要更改某些功能的类型,还是需要更改更多?
#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;
}
}
It is necessary to pass as a parameter to "insert" function a pointer to the "struct LinkedList" pointer... not the "struct LinkedList" pointer itself.有必要将一个指向“struct LinkedList”指针的指针作为参数传递给“插入”function……而不是“struct LinkedList”指针本身。
Additionally, you are only calling "insert()" once in this version so you don't see and your "insert()" is not creating the linked list.此外,您在此版本中只调用了一次“insert()”,因此您看不到并且您的“insert()”没有创建链接列表。 Instead it is overwriting the "head" (your "A" pointer) every time it is called.相反,它每次被调用时都会覆盖“head”(你的“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("%d\n", temp->data);
temp = temp->next;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.