Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
自己的代码:
public static ListNode1 deleteDuplicates(ListNode1 head) {
if(head == null) return null;
ListNode1 cur = head;
ListNode1 first = head;
while(cur != null) {
while(first != null && cur.val == first.val) // 寻找最近的下一个不同的节点
first = first.next;
cur.next = first;
if(cur != null) cur = cur.next; // 注意非空判断
}
return head;
}
别人的代码:
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)return head;
head.next = deleteDuplicates(head.next);
return head.val == head.next.val ? head.next : head;
}
核心思想:递归 -- 大问题 = 当前阶段 + 比大问题小一级的子问题