Remove every Duplicates from Sorted List

PROBLEM :

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* deleteDuplicates(struct ListNode* head) {
 
    struct ListNode* temp,*ptr,*curr ;
    if(head==NULL)
        return NULL;
    if(head->next==NULL)
        return head ;
     
    while(head!=NULL&&head->next!=NULL)
    {
        lable :
        if(head->val==head->next->val)
        {
            temp=head ;
            head=temp->next ;
            free(temp) ;
         
            if(head->next!=NULL&&head->val==head->next->val)
                goto lable ;
         
            temp=head ;
            head=temp->next ;
            free(temp) ;
        }
        else
            break ;
    }
 
    if(head==NULL)
        return NULL;
 
    temp=head ;
    while(temp!=NULL&&temp->next!=NULL)
    {
        lable2 :
        if(temp->val==temp->next->val)
        {
            ptr=curr->next ;
            curr->next=ptr->next ;
            free(ptr) ;
         
            temp=curr->next ;
         
            if(temp->next!=NULL&&temp->val==temp->next->val)
                goto lable2 ;
         
            ptr=curr->next ;
            curr->next=ptr->next ;
            free(ptr) ;
         
            temp=curr->next ;
        }
        else
        {
            curr=temp ;
            temp=temp->next ;
        }
    }
 
    return head ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )