zoukankan      html  css  js  c++  java
  • 83. Remove Duplicates from Sorted List

    • Total Accepted: 163106
    • Total Submissions: 417745
    • Difficulty: Easy
    • Contributors: Admin

    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.

    分析


    使用双指针, pre 和 cur,非递归
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            if(head == NULL || head->next == NULL) return head;
             
            ListNode* pre = head;
            ListNode* cur = head->next;
            while(cur != NULL){
                if(cur->val == pre->val){
                    ListNode * tmp = cur;
                    cur = cur->next;
                    pre->next = cur;
                    delete tmp;
                }
                else{
                    pre = pre->next;
                    cur = cur->next;
                }
            }
            return head;
        }
    };

    递归法
    删除head之后的list中重复元素,
    然后再比较,如果head->val == head->next->val
    则返回head->next
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
             if(head == NULL || head->next == NULL) return head;
             head->next = deleteDuplicates(head->next);
             if(head->next->val == head->val){
                ListNode* tmp = head;
                head = head->next;
                delete tmp;
             }
             return head;
        }
    };




  • 相关阅读:
    李永乐,皇帝的新衣背后,共有知识和公共知识
    汇率原理
    mybatis pageHelper 分页插件使用
    oracle中的exists 和not exists 用法详解
    Webservice入门简单实例
    java-可逆加密算法
    idea 卡顿问题
    idea svn操作
    HttpServletrequest 与HttpServletResponse总结
    Spring boot中应用jpa jpa用法
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/e717dc1f6ac78e9258dd9a762acea20c.html
Copyright © 2011-2022 走看看