c - 遍历链表

标签 c linked-list

我是 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 第一次迭代中,startlist 仍然相等,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/

相关文章:

C11_Generic 将 true 和 false 推导为整数

c - 如何使 Tru64 Unix 中的 C 代码在 Linux 64 位中工作?

Java 接口(interface) : Can an interface be used in a Linked list?

java - 创建字符串数组的链表

java - 自定义链接列表中的 JTable 数据存在问题

C 我怎样才能减少我的程序大小

C:难以理解这个基于文件/结构的指令

c - fprintf 在将其发送到文件时给出意外的输出

c - 链表-C-段错误

c - 插入链表 -