1. 程式人生 > >[Leetcode] Remove duplicate from sorted list ii 從已排序的鏈表中刪除重復結點

[Leetcode] Remove duplicate from sorted list ii 從已排序的鏈表中刪除重復結點

檢驗 等於 ron ret 說明 dup cat net col

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.

這題和Remove duplicate from sorted list的區別在於,本題中,只要結點只要出現重復則該值相等的結點都要刪除,上題中留一個不刪。

思路:這裏有可能有修改表頭(如:1->1->-1>2>3),一般修改表頭的題目都會需要一個輔助指針,所以要新建一個結點。遍歷鏈表,遇到相等的相鄰結點,直接繼續遍歷;遇到不相等的兩相鄰結點時,若pre->next=cur說明cur沒有重復的,pre=pre->next即可,若是不等於說明,可能有重復,則,pre連接cur但是pre不移動,需重新進入循環檢驗是否沒有重復(沒有重復時,pre->next=cur),直到沒有重復結點。源代碼

 1 class Solution {
 2 public:
 3     ListNode *deleteDuplicates(ListNode *head) 
4 { 5 if(head==NULL) return head; 6 7 ListNode *newList=new ListNode(-1); 8 newList->next=head; 9 ListNode *pre=newList; 10 ListNode *cur=head; 11 12 while(cur) 13 { 14 while(cur->next&&pre->next->val==cur->next->val)
15 { 16 cur=cur->next; 17 } 18 19 if(pre->next==cur) 20 pre=pre->next; 21 else 22 { 23 pre->next=cur->next; 24 } 25 26 cur=cur->next; 27 } 28 return newList->next; 29 } 30 };

[Leetcode] Remove duplicate from sorted list ii 從已排序的鏈表中刪除重復結點