【每日一题】83.删除排序链表中的重复元素

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

解法 1
和 26 题很像,使用类似的双指针法。

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;
    }
};

解法 2
因为是排过序的,一个指针就阔以了。

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

你可能感兴趣的:(LeetCode,leetcode,链表,单链表)