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

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

leetcode 82 删除排序链表中的重复元素_第1张图片

高频题

/**
 * 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* real_head = new ListNode(-1,head);
        ListNode* tmp_pre = real_head;
        ListNode* tmp = tmp_pre->next;
        int num = 0;
        
        if(tmp == nullptr || tmp->next == nullptr) return tmp;

        while(tmp_pre != nullptr && tmp != nullptr)
        {
            if(tmp_pre->next->val == tmp->val)
            {
                num = 0;
                while(tmp != nullptr &&  tmp_pre->next->val == tmp->val)
                {
                    num++;
                    tmp = tmp->next;
                }
                if(num > 1)
                {
                    tmp_pre->next = tmp;
                    continue;
                } 
                else tmp = tmp_pre->next;
            }   

            tmp_pre = tmp_pre->next;
            tmp = tmp->next;
        }

        return real_head->next;
    }
};

你可能感兴趣的:(高频题,链表,leetcode,数据结构)