gpt4 book ai didi

使用循环比较 2 个链表

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

我想比较两个链表。你能告诉我为什么我的代码不起作用吗?

如果两个列表不同,函数返回 0,如果相同则返回 1。

int compare(struct Node *list1, struct Node *list2)
{
struct Node *node1 = list1;
struct Node *node2 = list2;

while ((node1) || (node2))
if (node1->data != node2->data)
return 0;
else {
node1 = node1->next;
node2 = node2->next;
}

if ((node1 == NULL) && (node2 == NULL))
return 1;
else
return 0;
}

最佳答案

while 条件应该使用 && 而不是 || 因为您只希望它在 两个 列表仍然有更多节点时继续。 (顺便说一句,你过度使用括号了!)

int listEqual(struct Node *node1, struct Node *node2) {

while (node1 && node2) {
if (node1->data != node2->data)
return 0;
node1 = node1->next;
node2 = node2->next;
}

return node1 == NULL && node2 == NULL;
}

或者递归地(但这只有在你保证消除尾部调用的情况下才合理,例如使用 gcc -O2):

int listEqual(struct Node *node1, struct Node *node2) {
if (node1 == NULL && node2 == NULL)
return 1; // If both are NULL, lists are equal
if (node1 == NULL || node2 == NULL)
return 0; // If one is NULL (but not both), lists are unequal
if (node1->data != node2->data)
return 0;
return listEqual(node1->next, node2->next);
}

关于使用循环比较 2 个链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26663149/

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