• Remove Duplicates from sorted List


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

    Example 1:

    Input: 1->1->2
    Output: 1->2
    

    Example 2:

    Input: 1->1->2->3->3
    Output: 1->2->3

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    
    //时间复杂度O(n),空间复杂度:O(1)
    //递归版本
    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            if(!head) return head;
            ListNode dummy(head->val + 1);
            dummy.next = head;
            recur(&dummy,head);
            return dummy.next;
        }
        private:
            static void recur(ListNode* prev, ListNode *cur){
                if(cur == nullptr)  return;
                if(prev->val == cur->val){
                    prev->next == cur->next;
                    delete cur;
                    recur(prev,prev->next);
                }
                else{
                    recur(prev->next,cur->next);
                }
            }
    };
    
    
    //迭代版
    class Solution{
        public:
            ListNode* deleteDuplicates(ListNode *head){
                if(head == nullptr) return nullptr;
                
                for(ListNode* prev = head,*cur = head->next; cur; cur = prev->next){
                    if(prev->val == cur->val){
                        prev->next = cur->next;
                        delete cur;
                    }
                    else{
                        prev = cur;
                    }
                }
                return head;
            }
    };
    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    pom.xml 报错
    微信支付,提示当前页面URL未注册
    echarts + highcharts 柱状图
    二维码生成
    Eclipse
    SQLServer 安装及配置
    模板引擎doT.js用法详解
    SQL Server 笔记
    Flex 弹性盒模型
    查看Linux是Redhat 还是centos 还是...
  • 原文地址:https://www.cnblogs.com/hujianglang/p/11432575.html
Copyright © 2020-2023  润新知