0.簡介spa
本文是牛客網《劍指offer》筆記。指針
1.題目code
在一個排序的鏈表中,存在重複的結點,請刪除該鏈表中重複的結點,重複的結點不保留,返回鏈表頭指針。例如,鏈表1->2->3->3->4->4->5 處理後爲 1->2->5blog
2.思路排序
鏈表有0個節點索引
鏈表有1個節點內存
鏈表有2個以上節點io
三個指針和兩層循環實現刪除鏈表中重複的節點。class
首先,檢查邊界條件(鏈表有0個節點或鏈表有1個節點)時,返回頭結點;其次,避免因爲第一個節點是重複節點而被刪除,新建一個指向頭結點的節點;再次,創建三個指針pre/p/next,分別指向當前節點的前序節點、當前節點、當前節點的後續節點;最後循環遍歷整個鏈表,若是節點p的值和節點next的值相同,則刪除節點p和節點next,pre和下一個沒有重複的節點鏈接。若是節點p的值和節點next的值不一樣,則三個指針向後移動一個指針。List
3.code
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 }; 9 */ 10 class Solution { 11 public: 12 ListNode* deleteDuplication(ListNode* pHead) 13 { 14 // 鏈表有0個/1個節點,返回第一個節點 15 if(pHead==NULL||pHead->next==NULL) 16 return pHead; 17 else 18 { 19 // 新建一個頭節點,防止第一個結點被刪除 20 ListNode* newHead=new ListNode(-1); 21 newHead->next=pHead; 22 23 // 創建索引指針 24 ListNode* p=pHead; // 當前節點 25 ListNode* pre=newHead; // 當前節點的前序節點 26 ListNode* next=p->next; // 當前節點的後序節點 27 28 // 從頭至尾遍歷編標 29 while(p!=NULL && p->next!=NULL) 30 { 31 if(p->val==next->val)//若是當前節點的值和下一個節點的值相等 32 { 33 // 循環查找,找到與當前節點不一樣的節點 34 while(next!=NULL && next->val==p->val) 35 { 36 ListNode* temp=next; 37 next=next->next; 38 39 // 刪除內存中的重複節點 40 delete temp; 41 temp = nullptr; 42 43 } 44 45 pre->next=next; 46 p=next; 47 } 48 else//若是當前節點和下一個節點值不等,則向後移動一位 49 { 50 pre=p; 51 p=p->next; 52 } 53 next=p->next; 54 } 55 return newHead->next;//返回頭結點的下一個節點 56 } 57 } 58 };