zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    Ural 1966 Cycling Roads
    SQL Server 2008 安装(lpt亲测)
    cf Round#273 Div.2
    poj 2318 TOYS
    计算几何好模板
    ❤Friends
    限制pyqt5应用程序 只允许打开一次
    pyqt5 菜单栏+信息提示框
    Android Linux deploy
    system分区解锁
  • 原文地址:https://www.cnblogs.com/immjc/p/7234724.html
Copyright © 2011-2022 走看看