简体   繁体   中英

Why doesn't following code work for a linked list with just 2 nodes having same value?

The following function deletes duplicates in an unsorted linked list. It works for all cases except when the linked list has just two nodes which have duplicate values such as 10->10>NULL Can someone point me where I am going wrong ?

void deldup(struct node* head)
{
    struct node* outer = head;
    struct node* inner, *temp;

    while (outer->next != NULL && outer != NULL)
    {
        inner = outer;
        while (inner != NULL && inner->next != NULL)
        {
            if (inner->next->data == outer->data)
            {
                temp = inner->next;
                inner->next = inner->next->next;
                free(temp);
            }
            else
            {
                inner = inner->next;
            }
        }
        outer = outer->next;
    }
}

After deletion of the second 10, outer->next is null which gets assigned to outer. The next outer while loop condition tries to access outer->next first which crashes.

Solution: Reverse outer->next != NULL && outer != NULL into outer != NULL && outer->next != NULL . Remember, the second part of a logical AND isn't evaluated if the first one is false already, eactly for scenarios like this one.

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