我想比较两个链表.你能告诉我为什么我的代码不起作用吗?
如果两个列表不同,则函数返回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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
或递归(但如果你保证尾调用消除,这只是合理的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);
}
Run Code Online (Sandbox Code Playgroud)