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.

 

思路:P1 和P2.

 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==NULL) return NULL;
13         ListNode dumpHead(0);
14         ListNode *tail=&dumpHead, *p1=head, *p2=head->next;
15         bool flag=true;
16         while(p2!=NULL)
17         {
18             if(p1->val==p2->val)
19             {
20                 p2=p2->next;
21                 flag=false;
22                 continue;
23             }
24             
25             if(flag)
26             {
27              tail->next=p1;
28              tail=p1;
29              p1=p2;
30              p2=p2->next;
31             }
32             else
33             {
34             p1=p2;
35             p2=p2->next;
36             flag=true;
37             }
38         }
39         if(flag){tail->next=p1;p1->next=NULL;}
40         else tail->next=NULL;
41         return dumpHead.next;
42         
43     }
44 };

update: remove the flag. 判断p1->next==p2就可以知道中间有没有重复的。

 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==NULL) return NULL;
13         ListNode dumpHead(0);
14         ListNode *tail=&dumpHead, *p1=head, *p2=head->next;
15         while(p2!=NULL)
16         {
17             if(p1->val==p2->val)
18             {
19                 p2=p2->next;
20                 continue;
21             }
22             
23             if(p1->next==p2)//no same node detected
24             {
25              tail->next=p1;
26              tail=p1;
27              p1=p2;
28              p2=p2->next;
29             }
30             else//same node detected
31             {
32             p1=p2;
33             p2=p2->next;
34             }
35         }
36         if(p1->next==p2){tail->next=p1;}
37         else tail->next=NULL;
38         return dumpHead.next;
39         
40     }
41 };

 

posted @ 2014-07-07 13:16  Hicandyman  阅读(132)  评论(0)    收藏  举报