gpt4 book ai didi

c - 链表中出现无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 05:28:11 24 4
gpt4 key购买 nike

我有一个链表,其中包含一个遍历列表并打印出链表中结构值的方法。

void testLinkedList(LinkedList* list)
{
int count = 1;
LinkedListNode* current = list->head;
while (current != NULL)
{
printf("%d: Label is is %d\n", count, current->data->label);
current = current->next;
count++;
}
}

我在循环中做错了什么吗?它应该在到达最后一个节点时结束,但只要我允许,它就会继续循环并打印出魔数(Magic Number)。

编辑:这是我用来发送到链表的 insertlast() 函数:

void insertLast(LinkedList* list, TinCan* newData)
{
int ii = 1;
LinkedListNode* newNode = (LinkedListNode*)malloc(sizeof(LinkedListNode));
newNode->data = newData;

//check if queue empty
if(list->head == NULL)
{
list->head = newNode;
newNode->next=NULL;
}
else
{
LinkedListNode* current = list->head;
while (current->next != NULL)
{
current = current->next;
}
current->next = newNode;
printf("%d", ii);
ii++;
}
}

最佳答案

您在创建新列表节点时忘记将 next 指针设置为 NULL:

LinkedListNode* newNode = (LinkedListNode*)malloc(sizeof(LinkedListNode));
newNode->data = newData;
newnode->next = NULL;

顺便说一句:源代码的其余部分可以在 this 中找到相关主题。

关于c - 链表中出现无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16332100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com