C 使用循环比较2个链表
我想比较两个链表。你能告诉我为什么我的代码不起作用吗 如果两个列表不同,则函数返回0;如果两个列表相同,则函数返回1C 使用循环比较2个链表,c,C,我想比较两个链表。你能告诉我为什么我的代码不起作用吗 如果两个列表不同,则函数返回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->d
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条件应该使用
&&
而不是| |
,因为只有当两个列表仍有更多节点时,才希望它继续。(顺便说一句,你已经不用括号了!)
或者递归地(但这只有在保证尾部调用消除的情况下才是合理的,例如使用gcc-O2
):
while条件应该使用
&&
而不是| |
,因为只有当两个列表仍有更多节点时,才希望它继续。(顺便说一句,你已经不用括号了!)
或者递归地(但这只有在保证尾部调用消除的情况下才是合理的,例如使用gcc-O2
):
嘿,伙计,你能提供完整的代码吗。我无法单独测试此方法。while条件应使用
&&
而不是|
。顺便说一句,你已经不用括号了@ooga也许,这是第一次while loop。嘿,伙计,你能提供完整的代码吗。我无法单独测试此方法。while条件应使用&&
而不是|
。顺便说一句,你已经不用括号了@哦,也许是第一个while循环。第一个答案很好。然而,甚至想到使用递归遍历链表,我都会感到痛苦。孩子们,请不要在家里这样做。@JS1说得好!我在这里假设尾部呼叫消除。(最近一直在使用lisp。)我忘了提到我的链表实际上包含char*type@viethaihp291在这种情况下,您需要使用strcmp
来比较字符串:if(strcmp(node1->data,node2->data)!=0)返回0代码>第一个答案很好。然而,甚至想到使用递归遍历链表,我都会感到痛苦。孩子们,请不要在家里这样做。@JS1说得好!我在这里假设尾部呼叫消除。(最近一直在使用lisp。)我忘了提到我的链表实际上包含char*type@viethaihp291在这种情况下,您需要使用strcmp
来比较字符串:if(strcmp(node1->data,node2->data)!=0)返回0代码>
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;
}
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);
}