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; } }
1. 首先添加一個頭節點,以方便碰到第一個,第二個節點就相同的狀況java
2.設置 pre ,last 指針, pre指針指向當前肯定不重複的那個節點,而last指針至關於工做指針,this
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } */ 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; } }