• Remove Duplicates from Sorted List 分类: Leetcode(链表) 2015-03-03 21:16 30人阅读 评论(0) 收藏


    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.


    /**
     * 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) {
            ListNode *p;
            if(!head || !head->next) return head;
            p=head;
            while(p->next)
            {
                if(p->val==p->next->val)
                {
                    p->next=p->next->next;
                }
                else
                {
                    p=p->next;        
                }
            }
            return head;
        }
    };

    class Solution {
    public:
        ListNode *deleteDuplicates(ListNode *head) {
            if(head == NULL) return NULL;
            for (ListNode *prev = head, *cur = head->next; cur; cur = cur->next) {
                if(prev ->val == cur->val) {
                    prev->next = cur->next;
                    delete cur;
                } else {
                    prev = cur;
                }
            }
            return head;
        }
    };

    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 == NULL) return ;
            
            if (prev->val == cur->val) {
                prev ->next = cur->next;
                delete cur;
                return(prev, prev->next);
            } else {
                retcur( prev->next, cur->next);
            }
        }
    };




    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    distroless 镜像介绍及调试基于distroless 镜像的容器
    C# 设置或验证 PDF中的文本域格式 E
    Java 在PDF中添加工具提示|ToolTip E
    MongoDB Security
    Spring Boot MongoDB
    MongoDB 安装
    nginx重试机制proxy_next_upstream
    (转)VC中等比例缩放图像
    5 Ways You can Learn Programming Faster
    如何批量去除文件名中的某些字符串?
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656951.html
Copyright © 2020-2023  润新知