leetcode82 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 /**
 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)
13             return NULL;
14         ListNode *ans=new ListNode(0);
15         ListNode *p=ans;
16         int cur=head->val;
17         int count=1;
18         head=head->next;
19         while(head)
20         {
21             if(head->val!=cur)
22             {
23                 if(count==1)
24                 {
25                     ListNode *temp=new ListNode(cur);
26                     p->next=temp;
27                     p=p->next;
28                 }
29                 cur=head->val;
30                 count=1;
31             }
32             else
33             {
34                 count++;
35             }
36             head=head->next;
37         }
38                 if(count==1)
39                 {
40                     ListNode *temp=new ListNode(cur);
41                     p->next=temp;
42                     p=p->next;
43                 }
44         return ans->next;
45     }
46 };
View Code
原文地址:https://www.cnblogs.com/jsir2016bky/p/5105981.html