题目描述:在一个排序的链表中,删除重复的节点
思路及代码
public ListNode deleteDuplication(ListNode head) {
// 边界条件
if (head == null || head.next == null) return head;
ListNode next = head.next;
// 当 head.val 与后续值相等时,继续向后查找,直到找到一个与 head.val 不相等的节点
if (head.val == next.val) {
while (next.val == head.val && next != null)
next = next.next;
// 此处递归调用 deleteDuplication()
// 作用:1.删除头节点以及值和头节点相等的节点
// 2.将 next 作为头节点继续查找
return deleteDuplication(next);
} else {
// 头节点的值与后续节点的值不相等:将头节点的下一节点指向后续链表的头节点
// 该后续链表为不含重复值的链表
head.next = deleteDuplication(head.next);
return head;
}
}