[LeetCode] Remove Duplicates from Sorted List

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

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

给定一个含有重复元素的有序的列表,要求去除里面的重复元素。先判断边界条件,如果列表为空,或者列表只含有1个元素,则返回给定列表。接着使用一个cur指针遍历列表。如果遍历到重复元素,则删除该元素。如果没有遍历到重复元素,则让cur指针指向下一个元素。

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* cur = head;
        while (cur != nullptr && cur->next != nullptr) {
            if (cur->val == cur->next->val)
                cur->next = cur->next->next;
            else
                cur = cur->next;
        }
        return head;
    }
};
// 9 ms

也可以使用简洁的递归写法。

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return head;
        head->next = deleteDuplicates(head->next);
        return head->val == head->next->val ? head->next : head;
    }
};
// 13 ms
原文地址:https://www.cnblogs.com/immjc/p/7234724.html