Saturday, October 19, 2013

Remove Duplicates from Sorted List II [Leetcode]

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.

Solution: pointer manipulation but you may need to be quite careful...

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(head==NULL||head->next==NULL)
            return head;
        ListNode* pre = NULL;
        ListNode* cur = head;
        while(cur!=NULL){
            if(cur->next==NULL)
                return head;
            if(cur->val==cur->next->val){ //delete duplicates
                int tmp = cur->val;
                while(cur!=NULL && cur->val==tmp){
                    ListNode* delNode = cur;
                    cur = cur->next;
                    delete delNode;
                }
                if(cur==NULL){
                    if(pre==NULL)
                        return NULL;
                    else{
                        pre->next = NULL;
                        return head;
                    }
                }
                if(pre==NULL)
                    head = cur;
                else
                    pre->next = cur;
                continue;
            }
            //no duplicates
            pre = cur;
            cur = cur->next;
        }
        return head;
    }
};

No comments:

Post a Comment