解题思路1:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
//0结点或者1结点直接返回
if(pHead == null || pHead.next == null){
return pHead;
}
if(pHead.val == pHead.next.val){
/**当前节点是重复结点**/
ListNode node = pHead.next;
while(node != null && pHead.val == node.val){
node = node.next;
}
//从第一个与当前结点不同的结点开始递归
return deleteDuplication(node);
}else{
/**当前节点是不重复结点**/
//保留当前结点,从下一个节点开始递归
pHead.next = deleteDuplication(pHead.next);
return pHead;
}
}
}
解题思路2:
import java.util.*;
/*
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 first = new ListNode(-1);
first.next = pHead;
//记录最后一个节点位置
ListNode last = first;
while(pHead != null && pHead.next != null){
if(pHead.val == pHead.next.val){
int val = pHead.val;
while(pHead != null && val == pHead.val)
pHead = pHead.next;
last.next = pHead;
}else{
last = pHead;
pHead = pHead.next;
}
}
return first.next;
}
}