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:http://www.cplusplus.com/doc/tutorial/dynamic/

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;  
   while(cur->next!=NULL){  
     if(cur->data == cur->next->data)  
       cur->next = cur->next->next;   
     else  
     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..... :) :) :)

3 comments:

  1. Thank you, I had been looking for some online reference to be used in my Java training and your work really helped me.
    J2EE Training in Chennai | J2EE Training in Chennai | J2EE Training in Chennai

    ReplyDelete
  2. you are a great master! thankd for advice! I appreciate this. To enrich your vocabulary,visit research paper editing service - edit-ing.services, you won't regret! this site is a real miracle!

    ReplyDelete
  3. https://goo.gl/WUYHgA

    Maybe this is better, sir.

    ReplyDelete