【每日一题】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

发布了98 篇原创文章 · 获赞 91 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Hanoi_ahoj/article/details/105476180
今日推荐