我是 C 的新手,现在我正在尝试学习链表的基础知识。下面的代码只是遍历一个链表的片段。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int item;
struct node *next;
};
int main()
{
struct node *start,*list;
int i;
start = (struct node *)malloc(sizeof(struct node));
list = start;
start->next = NULL;
for(i=0;i<10;i++)
{
list->item = i;
printf("%p\t%p\n",start->next,list->next);
list->next = (struct node *)malloc(sizeof(struct node));
list = list->next;
}
return 0;
}
我很困惑“start->next”的输出不是NULL,而是一个固定的常量地址。但是我在for循环之前给start->next赋了NULL,只改变了“list”中的组件(list->item和list->next),而不是“start”中的组件。那么为什么“开始”中的组件发生了变化呢?
最佳答案
记住你有:list = start
:然后它们都指向同一个节点,只要它们相等,list->next
就是相同的作为 start->next
。
在 for
第一次迭代中,start
和 list
仍然相等,start->next
将为 NULL直到你赋值:list->next = ...
。
在第一次分配之后,start->next
将被修改为指向 malloced 地址。
在下一次迭代中,list
指向其他位置,修改 list->next
不会影响 start->next
。
一步一步:(“节点X”是我给malloc分配的节点的名字,它们不是你程序中的变量)
node 0: { .item = ?, .next = NULL } <---- start, list
i = 0;
list->item = i;
node 0: { .item = 0, .next = NULL } <---- start, list
list->next = malloc(...)
node 0: { .item = 0, .next = &(node 1) } <---- start, list
node 1: { .item = ?, .next = ? } <---- start->next, list->next
list = list->next
node 0: { .item = 0, .next = &(node 1) } <---- start
node 1: { .item = ?, .next = ? } <---- start->next, list
i = 1;
list->item = i;
node 0: { .item = 0, .next = &(node 1) } <---- start
node 1: { .item = 1, .next = ? } <---- start->next, list
list->next = malloc(...)
node 0: { .item = 0, .next = &(node 1) } <---- start
node 1: { .item = 1, .next = &(node 2) } <---- start->next, list
node 2: { .item = ?, .next = ? } <---- list->next
list = list->next;
node 0: { .item = 0, .next = &(node 1) } <---- start
node 1: { .item = 1, .next = &(node 2) } <---- start->next
node 2: { .item = ?, .next = ? } <---- list
等等
关于c - 遍历链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38239195/