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

Example

Let us see the following implementation to get better understanding −

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){
            //cout <"Adding!" << endl;
            dummyPtr->next = head;
            ListNode* temp = head->next;
            head->next = NULL;
            head = temp;
            dummyPtr = dummyPtr->next;
         } else {
            prev = head;
            head = head->next;
            //cout << "HEre!" << endl;
            while(head && head->val == prev->val){
               prev = head;
               head = head->next;
            }
         }
      }
      dummy->next;
   }
};

Input

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

Output

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