题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
解题思路
- 递归实现
- 当前结点为重复结点,找到值不等于当前结点的第一个结点,对该结点递归操作
- 当前结点不是重复结点,保留当前结点并对其下一个结点递归操作
代码实现
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function deleteDuplication(pHead)
{
// write code here
if(!pHead || !pHead.next){
return pHead;
}
if(pHead.val==pHead.next.val){//当前结点为重复结点
let pNode = pHead.next;
while(pNode && pNode.val == pHead.val){
pNode=pNode.next; //从值不等于当前结点的值的第一个节点递归
}
return deleteDuplication(pNode);
}else{//当前节点不是重复结点
pHead.next=deleteDuplication(pHead.next); //保留当前结点,从下一个节点开始递归
return pHead;
}
}