方法一:遞歸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){ // 只有0個或1個結點,則返回 return pHead; } if(pHead.val==pHead.next.val){ // 當前結點是重複結點 ListNode pNode=pHead.next; while(pNode!=null && pNode.val==pHead.val){ // 跳過值與當前結點相同的所有結點,找到第一個與當前結點不一樣的結點 pNode=pNode.next; } return deleteDuplication(pNode); // 從第一個與當前結點不一樣的結點開始遞歸 }else{ pHead.next=deleteDuplication(pHead.next); // 保留當前結點,從下一個結點開始遞歸 return pHead; } } }
方法二:設置指針spa
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } */ public class Solution { public ListNode deleteDuplication(ListNode pHead){ ListNode pPreHead=new ListNode(-1); //設立虛擬頭結點,由於頭結點可能會被刪掉 pPreHead.next=pHead; ListNode pre=pPreHead; ListNode cur=pHead; while(cur!=null && cur.next!=null){ if(cur.val==cur.next.val){ int val=cur.val; while(cur!=null && cur.val==val){//與當前結點相同的結點都跳過,重複的節點全不保留 cur=cur.next; } pre.next=cur; }else{ pre=cur; cur=cur.next; } } return pPreHead.next; } }