83. Remove Duplicates from Sorted List*

83. Remove Duplicates from Sorted List*

https://leetcode.com/problems/remove-duplicates-from-sorted-list/

Title Description

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

C ++ implementation 1

The title list is preferably introduced into the virtual node to do new list stored in the dummy, each time a new access node head, it is added to prevthe back, then while (head && head->val == prev->val)filtered duplicate nodes.

Finally there is the focus to be set prev->next = nullptr;, this can not be forgotten.

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) return nullptr;
        ListNode* dummy = new ListNode(0);
        auto prev = dummy;
        while (head) {
            prev->next = head;
            prev = prev->next;
            head = head->next;
            while (head && head->val == prev->val) head = head->next;
        }
        prev->next = nullptr;
        return dummy->next;
    }
};
Published 455 original articles · won praise 8 · views 20000 +

Guess you like

Origin blog.csdn.net/Eric_1993/article/details/104937013