Saturday 10 June 2017

Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head == NULL || head->next == NULL){
            return head;
        }
        //create a dummy node to avoid the case of head value getting repeated which is difficult to handle
        struct ListNode *res = new struct ListNode(0);
        res->next = head;
        
        struct ListNode *cur = res;
        while(cur->next && cur->next->next){
            //if the next value is same as its next value
            if(cur->next->val == cur->next->next->val){
                int val = cur->next->val;
                //move forward if same value is repeating
                while(cur->next && cur->next->val == val){
                    cur->next = cur->next->next;
                }
            }else{
                cur = cur->next;
            }
        }
        //return next of the dummy node
        return res->next;
    }
};
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts