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.

分析:将前一个数与后一个数比较,如果不同且出现次数为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)