刪除鏈表中重複的節點

解題思路:java

  1. 咱們每次都判斷當前結點的值與下一個節點的值是否重複
  2. 若是重複就循環尋找下一個不重複的節點,將他們連接到——新鏈表的尾部(其實就是刪除重複的節點)

 

public ListNode deleteDuplication(ListNode pHead) {
    if (pHead == null || pHead.next == null)
        return pHead;
    ListNode next = pHead.next;
    if (pHead.val == next.val) {
        while (next != null && pHead.val == next.val)
            next = next.next;
        return deleteDuplication(next);
    } else {
        pHead.next = deleteDuplication(pHead.next);
        return pHead;
    }
}

非遞歸版:code

public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
if (pHead==null || pHead.next==null){return pHead;}
ListNode Head = new ListNode(0);
Head.next = pHead;
ListNode pre  = Head;
ListNode last = Head.next;
while (last!=null){
    if(last.next!=null && last.val == last.next.val){
        // 找到最後的一個相同節點
        while (last.next!=null && last.val == last.next.val){
            last = last.next;
        }
        pre.next = last.next;
        last = last.next;
    }else{
        pre = pre.next;
        last = last.next;
    }
}
return Head.next;
}
}

blog

相關文章
相關標籤/搜索