gpt4 book ai didi

c - 反转链表错误

转载 作者:行者123 更新时间:2023-11-30 20:14:07 25 4
gpt4 key购买 nike

我编写的用于反转单链表的以下函数有什么问题?

struct ListNode* reverse_ll(struct ListNode *head)
{
struct ListNode *temp,*node,*prev;
temp=head->next;
head->next=NULL;
prev=head;
while(temp)
{
node=temp->next;
temp->next=prev;
prev=temp;
temp=node;
}
return prev;
}

最佳答案

如果您没有忘记分配新的 head 指针,那么反转列表的代码就可以工作:

head = reverse_ll(head);

正如 @user3553031 已经怀疑的那样,您的 printlist 函数无法正常工作。它不会打印最后一个元素。更改 while 的条件。您在这里也不需要“he​​ad”变量:

void printlist(struct ListNode *curr)
{
while (curr) {
printf("%d ", curr->data);
curr = curr->next;
}
putchar('\n');
}

最后,关于一致性的说明:如果反转列表的函数称为 reverse_ll,那么您的打印函数可能应该称为 print_ll

关于c - 反转链表错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27762877/

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