刪除連結串列中重複的結點
阿新 • • 發佈:2019-01-28
- 在一個排序的連結串列中,存在重複的結點,請刪除該連結串列中重複的結點,重複的結點不保留,返回連結串列頭指標。 例如,連結串列1->2->3->3->4->4->5 處理後為 1->2->5
- 應該注意的情況是需要保證記下需要刪除節點的前一個節點,要不然無法徹底刪除所有節點:
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead == null || pHead.next == null)
return pHead;
ListNode helper = new ListNode(-1);
helper.next = pHead;
ListNode prev = helper, curr = pHead, next = pHead.next;
while(curr != null && next != null){
if(next.val != curr.val){
prev = curr;
curr = next;
next = next.next;
}else {
while(next != null && next.val == curr.val)
next = next.next;
curr = prev.next = next;
if(next != null)
next = next.next;
}
}
return helper.next;
}
}