1. 程式人生 > >82.Remove Duplicates from Sorted List II

82.Remove Duplicates from Sorted List II

col display del 區別 open 分享 bsp etc close

題目鏈接

題目大意:刪除有序單鏈表中所有重復的數字,將非重復的數字留下來。與83有點 區別。

法一:記錄前面的重復節點,將當前結點與下一個節點和上一個重復節點進行比較,(因為可能出現3->3->3的情況),如果都不重復,則將節點保留,其他重復節點都刪除。代碼如下(耗時1ms):

技術分享圖片
 1     public ListNode deleteDuplicates(ListNode head) {
 2         //pre記錄前面最後一個重復的結點,cur進行遍歷
 3         ListNode res = null, cur = res, pre = null;
 4         while
(head != null) { 5 //如果前後節點重復則跳過,即刪除 6 if(head.next != null && head.val == head.next.val) { 7 pre = head; 8 head = head.next.next; 9 } 10 //如果當前節點與上一個節點重復,則刪除 11 else if(pre != null && head.val == pre.val) {
12 head = head.next; 13 } 14 //如果不重復,則將結點保留 15 else { 16 //尾插 17 if(cur == null) { 18 cur = head; 19 res = cur; 20 } 21 else { 22 cur.next = head;
23 cur = head; 24 } 25 head = head.next; 26 } 27 } 28 if(cur == null) { 29 return null; 30 } 31 cur.next = null; 32 return res; 33 }
View Code

82.Remove Duplicates from Sorted List II