给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
输入: 1->1->2
输出: 1->2
输入: 1->1->2->3->3
输出: 1->2->3
递归
- 递归结束条件:要么为空,要么
head.next
为空 - 递归到最后,返回时候判断当前节点与下一个节点的val是否相等
- 如果相等,则返回下一个节点
- 如果不相等,则返回当前节点
let deleteDuplicates = head => {
if (head === undefined || head.next == null) return head;
head.next = deleteDuplicates(head.next);
return head.val === head.next.val ? head.next : head;
}
func deleteDuplicates(head *ListNode) *ListNode {
if head == nil || head.Next == nil{
return head
}
head.Next = deleteDuplicates(head.Next)
if head.Val == head.Next.Val {
return head.Next
}
return head
}
class Solution {
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;
}
}