[Daily question] 83. Delete the duplicate elements in the sorted linked list

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

Solutions 1
and 26 are similar, using a similar two-pointer method.

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == nullptr || head->next == nullptr) return head;
        ListNode* s = head;
        ListNode* f = head->next;
        while (f != nullptr) {
            if (s->val == f->val) {
                ListNode* tmp = f->next;
                s->next = tmp;
                delete f;
                f = tmp;
            } else {
                s = f;
                f = f->next;
            }
        }
        return head;
    }
};

Solution 2 is
because the order is sorted, so a pointer is wide.

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == nullptr) { return head; }

        ListNode* cur = head;
        while (cur->next != nullptr) {
            if (cur->val == cur->next->val) {
                ListNode* tmp = cur->next;
                cur->next = tmp->next;
                delete tmp;
            } else {
                cur = cur->next;
            }
        }

        return head;
    }
};

EOF

98 original articles have been published · 91 praises · 40,000+ views

Guess you like

Origin blog.csdn.net/Hanoi_ahoj/article/details/105476180