Thursday, 23 April 2015

Remove duplicates in a sorted linked list


 Complexity O(n)

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

 


typedef struct Node * Node ;



void removeDuplicate (Node * head){
    if( head == NULL)
        return ;
    Node next_next = head->next ;
   
    while ( head -> next != NULL)
    {
        if( head->data == head->next->data)
        {
            //remove the next  duplicate node
            head->next = next_next->next;
            free(next_next);
            next_next = head->next ;
           
        }
        //advance only if no deletion occurs , because on deleting a node , we have no info about equality of the current and next (next_next) node
        else {
            head = head->next ;
        }
    }
}

No comments:

Post a Comment