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

Remove Duplicates from Sorted List II

时间:2015-04-28 20:12:03      阅读:118      评论: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.

分析:将前一个数与后一个数比较,如果不同且出现次数为1,则添加到结果里面。特别要注意最后一个结点:如果与前一个结点相同,则不必添加;如果与前一个结点不同,则必须要添加。运行时间14ms。思考:把line30~32为啥会出现wrong answer?

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* deleteDuplicates(ListNode* head) {
12         if(!head || !head->next) return head;
13         
14         ListNode *result = new ListNode(0);
15         ListNode *preHead = result;
16         int times = 1;
17         while(head->next){
18             if(head->val == head->next->val) times++;
19             else{
20                 if(times == 1){
21                     result->next = head;
22                     result = result->next;
23                 }
24                 times = 1;
25             }
26             head = head->next;
27         }
28         if(times == 1){
29             result->next = head;
30             result = result->next;
31         }
32         result->next = NULL;
33         
34         return preHead->next;
35     }
36 };

 

Remove Duplicates from Sorted List II

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4463591.html

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