[leetcode笔记] 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 class Solution {
 2 public:
 3     ListNode *deleteDuplicates(ListNode *head) {
 4         if (head==NULL || head->next==NULL)
 5             return head;
 6 
 7         ListNode *pDummyHead = new ListNode(0);
 8         pDummyHead->next = head;
 9 
10         ListNode *pNewHead = head;
11         ListNode *p = head;
12         ListNode *pLast = pDummyHead;
13         
14         bool bFoundHead = false;
15         while (p->next)
16         {
17             int nLastValue = p->val;
18             ListNode *pSub = p->next;
19             if (p->val != pSub->val)
20             {
21                 if (bFoundHead==false)
22                 {
23                     bFoundHead=true;
24                     pNewHead = p;
25                 }
26                 pLast = p;
27                 p = p->next;
28                 continue;
29             }
30             while (pSub && (pSub->val == nLastValue))
31             {
32                 ListNode *pToDelete = pSub;
33                 pSub = pSub->next;
34                 delete pToDelete;
35             }
36             ListNode *pToDelete = p;
37             p = pSub;
38             delete pToDelete;
39             pLast->next = pSub;
40             if (p==NULL)
41                 break;
42         }
43         if (bFoundHead==false)
44         {
45             pNewHead = p;
46         }
47         delete pDummyHead;
48         return pNewHead;
49     }
50 };

 

提交OJ,Accepted!

 

posted @ 2014-08-01 22:31  lequ  阅读(150)  评论(0编辑  收藏  举报