dimanche 22 mars 2020

Linked list concepts

Value of node in *node=*(node->next), if node is the last element in linked list?

Value of node would be NULL or not?

Q. Given a singly linked list consisting of N nodes. The task is to remove duplicates (nodes with duplicate values) from the given list (if exists). Note: Try not to use extra space. Expected time complexity is O(N). The nodes are arranged in a sorted way.

This solution didn't work for test case 2 2 2 2 2 (five nodes with equal values).

Node *removeDuplicates(Node *root)
{

    if(root->next==NULL)
        return root;

    Node * t1=root;
    Node* t2=root->next;
    while(t2!=NULL)
    {
        if(t1->data==t2->data)
        {

            *t2=*(t2->next);

        }else
        {
            t1=t1->next;
            t2=t2->next;
        }
    }
    return root;
}

This worked:

Node *removeDuplicates(Node *root)
{

    if(root->next==NULL)
        return root;

    Node * t1=root;
    Node* t2=root->next;
    while(t2!=NULL)
    {
        if(t1->data==t2->data)
        {
            if(t2->next==NULL)
            {
                t1->next=NULL;
                t2=NULL;
            }else{
                *t2=*(t2->next);
            }




        }else
        {
            t1=t1->next;
            t2=t2->next;
        }
    }
    return root;
}

Aucun commentaire:

Enregistrer un commentaire