Remove duplicates from an unsorted linked list

PROBLEM :

Remove duplicate element from an unsorted Linked List ..

Input:
You have to complete the method which takes 1 argument: the head of the  linked list  .You should not read any input from stdin/console. There are multiple test cases. For each test case, this method will be called individually.

Output:
Your function should return a pointer to a linked list with no duplicate element.

Constraints:
1 <=T<= 100
1 <= size of linked lists <= 50

Note: If you use "Test" or "Expected Output Button" use below example format.

Example:
Input
2
4
5 2 2 4
5
2 2 2 2 2

Output
5 2 4
2

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

/*

The structure of linked list is the following

struct Node
{
int data;
Node* next;
};

*/


Node *removeDuplicates(Node *root)
{
    Node *t1,*t2,*ptr,*prev ;
   
    if(root==NULL||root->next==NULL)
        return root;
    t1=root ;
    while(t1->next!=NULL)
    {
        prev=t1 ;
        t2=t1->next ;
        while(t2->next!=NULL)
        {
            if(t1->data==t2->data)
            {
                t2->data=t2->next->data ;
                ptr=t2->next ;
                t2->next=ptr->next ;
                free(ptr) ;
            }
            else
            {
                prev=t2 ;
                t2=t2->next ;
            }
        }
        if(t1->data==t2->data)
        {  
            free(t2) ;
            prev->next=NULL ;
        }
        if(t1->next!=NULL)
            t1=t1->next ;
    }
   
   return root ;
   
}



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

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 )