原题:#83_从有序链表中删除重复节点
- 解题思路:链表本身有序,所以若是有重复,那必是连在一起的
- 单指针(双指针类似):
public ListNode f (ListNode head) {
if (head == null)
return null;
ListNode cur = head;
while (cur != null && cur.next != null) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
- 递归:
- 结束条件:当前节点或下一节点为空
- 递归操作:比较当前节点与下一节点的值,若相等,则当前节点指向下下节点
- 返回值:返回已处理好的头指针
if (head == null || head.next == null) {
return head;
}
head.next = deleteDuplicates(head.next);
return (head.val == head.next.val) ? head.next : head;
}