Remove Duplicates from Sorted List II in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of some elements. We have to remove all elements that have occurred more than once. So only the distinct elements will remain in the list. So if the list is like [1,1,1,2,2,3,5,6,6,7,8], then the output will be [3,5,7,8], all other elements are present more than once.

Let us see the steps −

  • Create a dummy node with value -1, prev := NULL, dummyPtr := dummy
  • while head is not null
    • if next of head is present or the value of head is not same as the value of the next node, then
      • next of dummyPtr := head
      • temp := next of head, and make next of head null
      • head := temp
      • dummyPtr := next of dummyPtr
    • Otherwise
      • prev := head, and head := next of head
      • while head is not null and value of head = value of prev
        • prev := head and head := next of head
  • return the next of dummy

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode{
   public:
      int val;
      ListNode *next;
      ListNode(int data){
         val = data;
         next = NULL;
      }
   };
   ListNode *make_list(vector<int> v){
      ListNode *head = new ListNode(v[0]);
      for(int i = 1; i<v.size(); i++){
         ListNode *ptr = head;
         while(ptr->next != NULL){
            ptr = ptr->next;
         }
         ptr->next = new ListNode(v[i]);
      }
      return head;
   }
   void print_list(ListNode *head){
      ListNode *ptr = head;
      cout << "[";
      while(ptr){
      cout << ptr->val << ", ";
      ptr = ptr->next;
   }
   cout << "]" << endl;
}
class Solution {
   public:
   ListNode* deleteDuplicates(ListNode* head) {
      ListNode* dummy = new ListNode(-1);
      ListNode* prev = NULL;
      ListNode* dummyPtr = dummy;
      ListNode* nextNode;
      while(head){
         if(!head->next || head->val != head->next->val){
            dummyPtr->next = head;
            ListNode* temp = head->next;
            head->next = NULL;
            head = temp;
            dummyPtr = dummyPtr->next;
         } else {
            prev = head;
            head = head->next;
            while(head && head->val == prev->val){
               prev = head;
               head = head->next;
            }
         }
      }
   return dummy->next;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,1,1,2,2,3,5,6,6,7,8};
   ListNode *head = make_list(v);
   print_list(ob.deleteDuplicates(head));
}

Input

[1,1,1,2,2,3,5,6,6,7,8]

Output

[3, 5, 7, 8, ]
raja
Published on 03-Feb-2020 14:51:33
Advertisements