[leetcode笔记] Remove Duplicates from Sorted List II
生活随笔
收集整理的這篇文章主要介紹了
[leetcode笔记] Remove Duplicates from Sorted List II
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
問(wèn)題描述:
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.
?
解題筆記:
折騰了好多次,這次先寫(xiě)好很多測(cè)試用例,剛開(kāi)始總是不過(guò),總有情況未處理好,修改了多次后終于寫(xiě)成:
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!
?
轉(zhuǎn)載于:https://www.cnblogs.com/lequ/p/3885935.html
總結(jié)
以上是生活随笔為你收集整理的[leetcode笔记] Remove Duplicates from Sorted List II的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 堆栈中的EIP EBP ESP
- 下一篇: C语言 cgi(2)