Saturday, 18 April 2015

Hackerrank Delete duplicate-value nodes from a sorted linked list Solution

Problem Statement

This challenge is part of a tutorial track by MyCodeSchool
You're given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete as few nodes as possible so that the list does not contain any value more than once. The given head pointer may be null indicating that the list is empty.
For now do not be concerned with the memory deallocation. In common abstract data structure scenarios, deleting an element might also require deallocating the memory occupied by it. For an initial intro to the topic of dynamic memory please consult:

Source code:

  Remove all duplicate elements from a sorted linked list  
  Node is defined as   
  struct Node  
    int data;  
    struct Node *next;  
 Node* RemoveDuplicates(Node *head)  
  // This is a "method-only" submission.   
  // You only need to complete this method.   
   Node *cur = head;  
     if(cur->data == cur->next->data)  
       cur->next = cur->next->next;   
     cur = cur->next;  
   return head;  

** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)