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

Remove Duplicates from Sorted List II

时间:2016-12-07 02:07:29      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:判断   cat   bsp   利用   origin   nal   example   管理   dup   

Remove Duplicates from Sorted List II

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.

分析: 为了便于管理头指针,创建一个新的头指针,利用几个新的变量来判断cur和prev的关系

/**
 * 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 ==NULL)
            return head;
            
        ListNode* start = new ListNode(0);
        start->next = head;

        ListNode* cur = head;
        ListNode* prev = start;
        while(cur){
            while(cur->next && cur->next->val == prev->next->val)
                cur = cur->next;
            if(prev->next == cur)
                prev = cur;
            else
                prev->next = cur->next; 
            cur = cur->next;
        }
        return start->next;
    }
};

 

Remove Duplicates from Sorted List II

标签:判断   cat   bsp   利用   origin   nal   example   管理   dup   

原文地址:http://www.cnblogs.com/willwu/p/6139595.html

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