1.本题知识点
链表
2. 题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
3. 思路
充分利用递归思想 以及对象及引用的理解:
① 先考虑没有重复节点的情况,保留当前节点,从下一个节点开始递归,此时需要保留当前节点和其引用next指针。
② 有重复节点时,只保留重复节点中的最后一个,然后再次进行递归(此时相当于从新开始,不需要考虑其他因素)。
Java版本:
public class Solution {
public ListNode deleteDuplication(ListNode head)
{
if(head == null || head.next == null) return head;
if(head.val != head.next.val){
head.next = deleteDuplication(head.next);
return head;
}
else{
ListNode pNode = head.next;
while(pNode != null && pNode.val == head.val){
pNode = pNode.next;
}
return deleteDuplication(pNode);
}
}
}