我对这段代码的一部分不懂,请看代码(我不懂的地方我放在注释里面了):
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *create()
{
struct node *head;
struct node *tail;
struct node *p;
int x=0;
head=tail=NULL;
printf("请输入一个整数\n");
scanf("%d",&x);
while(x!=-1){
p=(struct node*)malloc(sizeof(struct node));
p->data = x;
p->next = NULL;
if(head==NULL) head=tail=p;
else{
tail->next=p;
/* 假设进入第二轮循环,输入了2,那么p->data是2,p->next=NULL;让tail->next=p 就是让tail的成员next指向这个新构建的p */
tail = p;
/*这里又让tail=p,那么此时的tail不应该是tail->data = 2; tail->next= NULL了吗?既然tail->next=null了,岂不是让上一个语句的 tail->next=p建立的连接失效了吗?*/
}
printf("请输入一个整数\n");
scanf("%d",&x);
}
return head;
}
int main(){
creat();
return 0;
}