个人博客:https://luxialan.com

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




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

posted @ 2015-03-03 21:16  luxialan  阅读(105)  评论(0编辑  收藏  举报