Delete Duplicate Values in a Linked List

 So we have a sorted Linked List for example -

1->2->3->3->4->5->6->6->6->7->8->NULL

We want to remove the duplicate values present in this linked list so that it comes out to be like- 

1->2->3->4->5->6->7->8->NULL

Alright so let's create a function assuming we already have the other said variables in place for the linked list.

Node* removeDuplicates(Node* head) {

    if(head==NULL || head->next==NULL) 

        return head;

    Node* root = head;

    while(head->next!=NULL){

       if(head->data!=head->next->data)

       {

           head = head->next;

       }

       else

       {

           head->next = head->next->next;

       }

    }

    return root  

}

Explanation in Steps-

  1. We first check whether the linked list is empty or not
  2. Next we create a new node called as root and set its value to head
  3. We iterate a loop until the NULL value in the linked list 
  4. As we go, we create an if condition to compare our data in the head node is not equal to the data in the next node, fulfilling this condition leads to the head moving one step ahead
  5. In case a similar value is found, we change the next head value to omit the next value and take in value of the input after the next value i.e. Next of next value.
  6. In the end we return the whole linked list without the duplicate values
And that is what i coded! 

Popular posts from this blog

Finding the Subarrays (Hackerearth)

Palindrome Index (Hackerrank)

Sherlock and Array (Hackerrank)