Reputation: 507
I want to compare two linked lists. Can you tell me why my code doesn't work?
The function returns 0 if the two lists are different, 1 if they're the same.
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;
}
Upvotes: 0
Views: 1993
Reputation: 15501
The while condition should use &&
instead of ||
since you only want it to continue if both lists still have more nodes. (BTW, you're over-using parentheses!)
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;
}
Or recursively (but this is only reasonable if you're guaranteed tail call elimination such as with 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);
}
Upvotes: 5