xinyu04

导航

LeetCode 82 Remove Duplicates from Sorted List II 链表删除重复元素

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

Solution

我们需要删除重复的元素,我们新建一个节点,然后用 \(p\) 来指向新的list, \(cur\) 来指向原来的list。如果有重复的元素,我们直接移动到下一位,然后将上一个给 \(delete\)

点击查看代码
/**
 * 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 newhead(0, head);
        ListNode* p = &newhead, *cur = head;
        
        while(cur){
            ListNode* next_node = cur->next;
            while(next_node && next_node->val == cur->val ){
                // same values
                ListNode* tmp = next_node->next;
                delete next_node;
                next_node = tmp;
            }
            
            if(cur->next == next_node){
                p = cur;
            }
            else{
                p->next = next_node;
            }
            cur = next_node;
        }
        return newhead.next;
    }
};

posted on 2022-07-30 17:11  Blackzxy  阅读(4)  评论(0编辑  收藏  举报