Sunday, July 12, 2015

Leetcode 83: 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.

跟array remove duplicates类似, 这里重复的元素一个不剩的情况,对于当fast != slow的时候,有两种情况,一种是如果fast前面有duplicate的元素,那么直接fast->slow,如果fast前面没有duplicate的元素,那么需要slow++, 然后fast->slow。 所以需要一个flag 标志,如果有duplicate, flag = true,如果没有duplicate: flag = false;最后对链表的处理,如果flag == true, 表明最后还处于duplicate的情况下,那么slow所指的node是不应该要的,如果flag == false,表明最后的slow指向的node是应该留下的,特别对于{1,1}这类情况,return NULL。

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        //sanity cehck
        if (head == NULL || head->next == NULL) return head;
        ListNode* slow = head;
        ListNode* fast = head->next;
        bool flag = false;
        ListNode* pre = NULL;
        while(fast != NULL) {
            if (fast->val != slow->val) {
                if (flag == false) {
                    pre = slow;
                    slow = slow->next;
                    slow->val = fast->val;
                } else if (flag == true) {
                    slow->val = fast->val;
                    flag = false;
                }
            } else{
                flag = true;
            }
            fast = fast->next;
        }
        if (flag == false) slow->next = NULL;
        else if(pre) pre->next = NULL;
        else return NULL;
        return head;
    }
};

No comments:

Post a Comment