码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates from Sorted List II -- leetcode

时间:2015-04-18 13:11:39      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:leetcode   链表   去重   

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,

Given 1->2->3->3->4->4->5, return 1->2->5.

Given 1->1->1->2->3, return 2->3.



写法一

设置前后两个指针, 后指针,指向没有重复的最后一个元素。

另一指针指向当前元素。

当遇到重复元素时,一直移动当前指针。

通过判断当前指针有没有移动过,可得知,当前元素是否为重复元素。

如果没有移动,则不是重复元素。接受他,即将后指针指向该元素。

此代码在leetcode上实际运行时间为14ms。


/**
 * 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 fake(0);
        ListNode *last = &fake;
        last->next = head;
        while (head) {
            head = head->next;
            while (head && head->val == last->next->val) {
                auto bak = head->next;
                delete head;
                head = bak;
            }
            
            if (last->next->next == head)
                last = last->next;
            else {
                delete last->next;
                last->next = head;
            }
        }
        
        return fake.next;
    }
};


写法二

此代码在leetcode上实际执行时间为16ms。

判断接下来两个元素是否重复。如果重复,进入重复分支处理。

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        ListNode fake(0);
        ListNode *last = &fake;
        last->next = head;
        while (head && head->next) {
            head = head->next;
            if (last->next->val == head->val) {
                while (head && last->next->val == head->val) {
                    last->next->next = head->next;
                    delete head;
                    head = last->next->next;
                }
                delete last->next;
                last->next = head;
            }
            else {
                last = last->next;
            }
        }
        
        return fake.next;
    }
};


Remove Duplicates from Sorted List II -- leetcode

标签:leetcode   链表   去重   

原文地址:http://blog.csdn.net/elton_xiao/article/details/45111815

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!