c - 具有导致无限循环的函数的链表

标签 c linked-list infinite-loop

我正在尝试制作一个简单的链表,只有一个函数和两个指针。

#include <stdio.h>
#include <stdlib.h>

typedef struct leonor{
    int x;
    struct leonor * next;
}leo;

出于练习的目的,我总是寻找列表的末尾以添加我创建的最后一个新节点。函数(添加)如下:

void add(leo **ad)
{
    int i;
    leo *current, *new, **previous; /*Previous points on the pointer NEXT
                                     *of an element*/

    new=malloc(sizeof(*new));

    for (i=0;i<3;i++)
    {
        printf("x : ");
        scanf("%d",&new->x);
        new->next=NULL;

        previous = ad; /*'previous' receives adresse of head of list*/
        current = *previous;

        while(current != NULL) /*Look for last element of list*/
        {
            previous = &(current->next);
            current = current->next;
        }

        new->next = *previous;
        *previous = new;
    }
}

其余代码:

void display_(leo *hl)
{
    while (hl)
    {
        printf("%d -> ",hl->x);
        hl=hl->next;
    }
}
int main()
{
    leo * head;
    head = NULL;
    add(&head);
    display_(head);
    return 0;
}

问题是在创建链表(这里是 3 个整数的列表)之后,它总是只包含最后输入的数字。并且在显示结果时是相同所述数字的无限循环。将不胜感激帮助。

最佳答案

您只需分配一个 struct leo 并为您添加的每个元素使用同一个。您需要为放入列表的每个元素分配一个新元素。

关于c - 具有导致无限循环的函数的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35384511/

相关文章:

java - 非常快地跳到双向链表的中间

java - 从单链表中删除节点

c - 使用尾指针插入链表的末尾,然后打印列表导致无限循环

c - 纯文本文件或加密文件(C编程)

c - json-c 解析 - 取消引用指向不完整类型的指针时出错

c - Winapi - 扩展键盘扫描码

MIPS:带分支的无限循环

c - 从钩子(Hook)函数返回挂起

c++ - 不确定如何反转我的堆栈?

java - 如何在后台线程中运行无限循环并重新启动它