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




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

  • 相关阅读:
    STL标准函数库学习小总结
    3 种生成高强度密码的方法
    树莓派使用 OLED 屏显示图片及文字
    一个骚命令防止你的文件被误删除!
    B站,首战告捷!
    10 个提高效率的 Linux 命令别名
    Vim的三款实用插件
    如何高效回退到特定层级目录?
    如何将目录下的脚本一次性全部执行
    数据结构|数组为什么这么快?
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656951.html
Copyright © 2011-2022 走看看