欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-20 19:35:17
...

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        unordered_map<int,int> mp;
        ListNode* cur = head;
        while(cur){
            mp[cur->val]++;
            cur = cur->next;
        }
        ListNode* dump = new ListNode();
        dump->next = head;
        ListNode *pre = dump;
        cur = head;
        while(cur){
            if(mp[cur->val]>1){
                pre->next = cur->next;
            }else{  
                pre = cur;
            }
            cur = cur->next;
        }
        return dump->next;
    }
};
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* dump = new ListNode;
        dump->next = head;
        ListNode* cur = head, *pre = dump;

        while(cur){
            if(cur->next && cur->val == cur->next->val){
                int val = cur->val;
                while(cur && cur->val == val){
                    cur = cur->next;
                }
                pre->next = cur;
            }else{
                pre = cur;
                cur = cur->next;
            }
        }
        return dump->next;
    }
};
相关标签: LeetCode # LC链表