Remove Duplicates from Sorted List

PROBLEM :

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2,              return 1->2.
Given 1->1->2->3->3,   return 1->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 *ptr ,*temp ;
        if(head==NULL)
            return ;
         
        temp=head ;
        while(temp->next!=NULL)
        {
            if(temp->val==temp->next->val)
            {
                ptr=temp->next ;
                temp->next=ptr->next ;
                free(ptr) ;
            }
            else
                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 )