LeetCode—82. Remove Duplicates from Sorted List II

Type:medium

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input:1->2->3->3->4->4->5Output:1->2->5

Example 2:

Input:1->1->1->2->3Output:2->3


给定一个排好序的链表,删去出现超过一次的所有节点。

判断head及head->next是否为空,若为空,返回head,结束。

首先设一个空的dummy节点指向head,用pre表示想要保留的节点,初始等于dummy,pre->next指向想要保留但未确定是否只出现一次的节点。cur指向当前遍历的节点。

当cur->next的val等于cur->val,cur向后遍历,直至cur-next-val不等于cur-val停止,此时判断pre-next是否与cur是同一个指针,若不等则pre-next指向cur-next,若相等则pre等于pre-next。最后返回dummy-next




ListNode* deleteDuplicates(ListNode* head) {

        if(!head || !head->next) return head;

        ListNode *dummy = new ListNode(-1);

        dummy->next = head;

        ListNode *pre = dummy;

        while(pre->next){

            ListNode *cur = pre->next;

            while(cur->next && cur->next->val == cur->val){

                cur = cur->next;

            }

            if(cur != pre->next) pre->next = cur->next;

            else pre = pre->next;

        }


        return dummy->next;

    }


你可能感兴趣的:(LeetCode—82. Remove Duplicates from Sorted List II)