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

【Remove Duplicates from Sorted List II 】cpp

时间:2015-04-29 21:09:45      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

题目

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.

代码

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

Tips:

主要思路就是:如果遇上相同的,就用while循环一直往后过。

具体思路沿用了之前Python版的:http://www.cnblogs.com/xbf9xbf/p/4186852.html

【Remove Duplicates from Sorted List II 】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4466832.html

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