思路:
1、当前节点 与 当前节点的下一个节点 相同时,该节点可删除。为了保证删除后链表不断,需要把当前节点的前一个节点和删除后的第一个节点相连接。
2、如果是头结点,则将删除后的第一个节点赋值给头结点。
public ListNode deleteDuplication(ListNode pHead){
//非空值的判断
if(pHead==null)
return null;
ListNode pPre=null;
ListNode pNode=pHead;
ListNode pNext=null;
while(pNode!=null){
pNext=pNode.next;
//重复节点删除
if(pNext!=null&&pNode.val==pNext.val){
//遍历到最后一个重复节点
while(pNext!=null&&pNode.val==pNext.val){
pNode=pNext;
pNext=pNode.next;
}
//删除的是否是头结点
if(pPre==null){
pHead=pNext;
}else{
pPre.next=pNext;
}
pNode=pNext;
}else{//非重复节点
pPre=pNode;
pNode=pNext;
}
}
return pHead;
}
注意点: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;
}
}