C语言 遍历链表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14757732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:17:33  来源:igfitidea点击:

Traversing through a linked list

cdata-structureslinked-list

提问by user1905568

#include<stdio.h>
struct node
{
    int item;
    struct node *link
};

main()
{
    struct node *start,*list;
    int i;
    start = (struct node *)malloc(sizeof(struct node));
    list = start;
    start->link = NULL;
    for(i=0;i<10;i++)
    {
        list->item = i;
    list->link = (struct node *)malloc(sizeof(struct node));
    }
    list->link = NULL;
    while(start != NULL)
    {
        printf("%d\n",start->item);
    start = start->link;
    }
}

As the title suggests in this i am trying to traverse through a linked list itteratively the expected output is 0 1 . . 9 and the observed output is : 9 What is wrong with the code ?

正如标题所暗示的那样,我试图迭代地遍历链表,预期输出为 0 1 。. 9 观察到的输出是: 9 代码有什么问题?

回答by jonhopkins

You aren't pointing listat the next node after you create it, so you're just overwriting the previous node each time. Try this:

list创建节点后,您不会指向下一个节点,因此每次都只是覆盖上一个节点。尝试这个:

for(i=0;i<10;i++)
{
    list->item = i;
    list->link = (struct node *)malloc(sizeof(struct node));
    list = list->link;
}

回答by Raj

It is just because of one statement in your code. You forgot to point to the next link, when you tried to allocate the new link. Because of that you were allocating only at one pointer, thus having memory leak.

这只是因为您的代码中的一个语句。当您尝试分配新链接时,您忘记指向下一个链接。因此,您只分配了一个指针,从而导致内存泄漏。

#include<stdio.h>
struct node
{
    int item;
    struct node *link
};

main()
{
    struct node *start,*list;
    int i;
    start = (struct node *)malloc(sizeof(struct node));
    list = start;
    start->link = NULL;
    for(i=0;i<10;i++)
    {   
        list->item = i;
        list->link = (struct node *)malloc(sizeof(struct node));
        list = list->link;
    }   
    list->link = NULL;
    while(start != NULL)
    {   
        printf("%d\n",start->item);
        start = start->link;
    }   
}