Skip to content

Latest commit

 

History

History
66 lines (48 loc) · 1.26 KB

83.删除排序链表中的重复元素.md

File metadata and controls

66 lines (48 loc) · 1.26 KB

83. 删除排序链表中的重复元素

url

题目

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

输入: 1->1->2
输出: 1->2
输入: 1->1->2->3->3
输出: 1->2->3

方法

递归

  • 递归结束条件:要么为空,要么head.next为空
  • 递归到最后,返回时候判断当前节点与下一个节点的val是否相等
  • 如果相等,则返回下一个节点
  • 如果不相等,则返回当前节点

code

js

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;
}

go

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
}

java

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;
    }
}