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.

Example

Given 1->2->3->3->4->4->5, return 1->2->5.

Given 1->1->1->2->3, return 2->3.

分析:

虽然需要一定的思考时间,但是确实可以一遍过。尽量别再开始的时候误入歧途,用while删除很好。

解法:

class Solution{
public:
    /**
     * @param head: The first node of linked list.
     * @return: head node
     */
    ListNode * deleteDuplicates(ListNode *head) {
        // write your code here
        if (head == NULL) {
            return NULL;
        }

        ListNode dummy(-1);
        dummy.next = head;

        ListNode* prev = &dummy;
        ListNode* curr = head;

        int checkValue = head->val - 1;

        while (curr != NULL && curr->next != NULL) {

            if (curr->val == curr->next->val) {

                checkValue = curr->val;
                while (prev->next != NULL && prev->next->val == checkValue) {
                    prev->next = prev->next->next;
                }
                curr = prev->next;

            } else {
                prev = prev->next;
                curr = curr->next;
            }
        }
        return dummy.next;
    }
};

results matching ""

    No results matching ""