typedef struct Student
{
int age;
int score;
struct Student * next;
}ST;
ST * create_list()
{
ST * head;
ST * tail;
int len, i;
head = (ST *)malloc( sizeof(ST) );
if(head == NULL)
{
printf("内存分配失败,程序退出!\n");
exit(-1);
}
tail = head;
tail->next = NULL;
printf("您想创建几个节点?\n");
scanf("%d", &len);
for(i=0; i<len; i++)
{
ST * pNew = (ST *)malloc( sizeof(ST) );
if(pNew == NULL)
{
printf("创建了%d个链表,剩余%d个创建失败,程序退出", i+1, len-1-i);
exit(-1);
}
printf("请输入第%d个学生的年龄和成绩\n", i+1);
scanf("%d %d", &pNew->age, &pNew->score);
tail->next = pNew;
tail = pNew;
pNew->next = NULL;
}
return head;
}
只截取了一部分,其中有这三行代码
tail->next = pNew;
tail = pNew;
pNew->next = NULL;
第一行的意思是将tail中的next域更新成新生成的节点,也就是让前一个节点的指针域指向新生成的节点,第二行执行的tail = pNew,不会将前一个节点的内容给覆盖,或者让前一个节点的内容丢失吗?我总想不通,假如说用户要建立两个节点,
在第一个建立完成后,继续第二次创建,也就是说第一次将pNew中的age和score赋给了tail中的age和score,那么第二次我觉得链表的节点指向好像没有更新啊,如果改成tail = tail->next我还能明白。那么tail = pNew,执行的到底是什么操作呢?求大神详解。
个人想法
现在就再糊涂中,先说int *a, *b;
假设b已经分配了一块合法的内存空间,a = b中b给a传递的是什么?在
tail->next = pNew;
tail = pNew;
中,是不是第一句才是将指针后移的操作呢?还是第二句呢?哎呀,彻底蒙了,求求我吧哥
head -> node1 -> node2 -> node3 pNew
^
|
tail
假设此时 tail 指向 node3,此时没有指针指向 pNew
head -> node1 -> node2 -> node3 -> pNew
^
|
tail
head -> node1 -> node2 -> node3 -> pNew
^
|
tail
现在可以把 pNew 看作 node4,
head -> node1 -> node2 -> node3 -> node4
^
|
tail
追问也就是说每一次的指针指向都是有指针移动的?
追答tail->next = pNew; // 这一步的效果如下:node3 指向了 pNew,注意tail 本身没有移动head -> node1 -> node2 -> node3 -> pNew
^
|
tail
head -> node1 -> node2 -> node3 -> pNew
^
|
tail