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




  • 相关阅读:
    基础练习 数列排序
    入门训练 Fibonacci数列
    入门训练 圆的面积
    入门训练 序列求和
    fzu 2111 Min Number
    入门训练 A+B问题
    历届试题 城市建设
    sort 树 hash 排序
    nyist 676 小明的求助
    快速幂 蒙格马利算法
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/e717dc1f6ac78e9258dd9a762acea20c.html
Copyright © 2011-2022 走看看