剑指offer--删除排序链表中的重复元素

删除一个元素有两个含义:一是删除这个元素,只出现一次;二是删除这个元素不再出现。

lleetcode 83 删除排序链表中的重复元素I

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* dummy = new ListNode(-1);
        dummy->next = head;
        ListNode* pre = dummy;//指向当前节点
        ListNode* cur = head; //指向下一个不一样值节点
        while(cur && cur->next){
            if(cur->val != cur->next->val){
                pre->next = cur;
                pre = cur;   
                cur = cur->next;
                continue;
            }
            while(cur->next && cur->val == cur->next->val)
                cur = cur->next;
            pre = pre->next; //注意,因为还要保留一个,因此pre要往前移
            cur = cur->next;
            pre->next = cur;
        }
        return dummy->next;
    }
};

leetcode 82 删除排序链表中的重复元素II

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* dummy = new ListNode(-1);
        dummy->next = head;
        ListNode* pre = dummy;
        ListNode* cur = head;
        while(cur && cur->next){
            if(cur->val != cur->next->val){
                pre->next = cur;
                pre = cur;   
                cur = cur->next;
                continue;
            }
            while(cur->next && cur->val == cur->next->val)
                cur = cur->next;
            //注意这里以上一道题的区别
            cur = cur->next;
            pre->next = cur;
        }
        return dummy->next;
    }
};

你可能感兴趣的:(剑指offer)