zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    };




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

  • 相关阅读:
    LeetCode456. 132模式
    LeetCode455. 分发饼干
    LeetCode454. 四数相加 II
    LeetCode453. 最小移动次数使数组元素相等
    matchMedia 媒体查询结果
    异常捕获
    常用xpath选择器和css选择器总结
    python-爬虫中的extract()
    Python应用前景广阔,怎么学才能快速上手?
    Python 为什么要有 pass 语句?
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656951.html
Copyright © 2011-2022 走看看