LeetCode 82,83 Remove Duplicates from Sorted List I, II解析

/************************************************************************
* Given a sorted linked list, delete all duplicates such that each element appear only once.
*
* For example,
* Given 1->1->2, return 1->2.
* Given 1->1->2->3->3, return 1->2->3.
************************************************************************/

 //注意的是1->2->1会输出1->2->1,它只要求去除连续的节点的重复值
 ListNode* deleteDuplicates(ListNode* head) {
        ListNode* cur = head;
        while(cur) {
            while(cur->next && cur->val == cur->next->val) {
                cur->next = cur->next->next;
            }
            cur = cur->next;
        }
        return head;
    }

/************************************************************************
* 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->1会输出1->2->1,它只要求去除连续的节点的重复值

因为要删除的可能是第一个结点,所以见一个伪结点来指向第一个节点,就比较好办了。

ListNode *deleteDuplicates(ListNode *head) {
        ListNode preHead(0);
        preHead.next = head;
        ListNode* pre = &preHead;
        ListNode* cur = pre->next;
        while (cur) {
            ListNode* nxt = cur->next;
            //若发生交换
            if (nxt&& cur->val == nxt->val) {
                // move pn to next different value
                while (nxt && cur->val == nxt->val) {
                    nxt = nxt->next;
                }
                //仔细理解,发生交换式并不改变pre节点
                cur = nxt;
                pre->next = cur;
            }
            else {   //为发生交换
                pre = cur;     // pre为cur,发生改变
                cur = cur->next;
            }
        }
        return preHead.next;
    }

你可能感兴趣的:(LeetCode)