Remove Duplicates from Sorted List II -- LeetCode
阿新 • • 發佈:2017-07-17
!= null 向上 clas cat ted 頭指針 方便 article
原題鏈接: http://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
這道題跟Remove Duplicates from Sorted List比較類似,僅僅是這裏要把出現反復的元素所有刪除。事實上道理還是一樣,僅僅是如今要把前驅指針指向上一個不反復的元素中,假設找到不反復元素,則把前驅指針知道該元素,否則刪除此元素。算法僅僅須要一遍掃描。時間復雜度是O(n),空間僅僅須要幾個輔助指針,是O(1)。 能夠看到,上述代碼中我們創建了一個輔助的頭指針。是為了改動鏈表頭的方便。前面介紹過,通常會改到鏈表頭的題目就會須要一個輔助指針,是比較常見的技巧。
這道題跟Remove Duplicates from Sorted List比較類似,僅僅是這裏要把出現反復的元素所有刪除。事實上道理還是一樣,僅僅是如今要把前驅指針指向上一個不反復的元素中,假設找到不反復元素,則把前驅指針知道該元素,否則刪除此元素。算法僅僅須要一遍掃描。時間復雜度是O(n),空間僅僅須要幾個輔助指針,是O(1)。
代碼例如以下:
public ListNode deleteDuplicates(ListNode head) { if(head == null) return head; ListNode helper = new ListNode(0); helper.next = head; ListNode pre = helper; ListNode cur = head; while(cur!=null) { while(cur.next!=null && pre.next.val==cur.next.val) { cur = cur.next; } if(pre.next==cur) { pre = pre.next; } else { pre.next = cur.next; } cur = cur.next; } return helper.next; }
Remove Duplicates from Sorted List II -- LeetCode