简体   繁体   中英

Compare 2 linked lists using loop

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;
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM