Skip to content

Latest commit

 

History

History
88 lines (64 loc) · 1.72 KB

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

File metadata and controls

88 lines (64 loc) · 1.72 KB

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

url

题目

存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现 的数字。

返回同样按升序排列的结果链表。

输入:head = [1,2,3,3,4,4,5]
输出:[1,2,5]

方法

code

js

let deleteDuplicates = head => {
    if (head === null || head.next === null)
        return head;
    let next = head.next;
    if (head.val === next.val) {
        while (next !== null && head.val === next.val)
            next = next.next;
        return deleteDuplicates(head);
    } else {
        head.next = deleteDuplicates(head.next);
        return head;
    }
}

go

func deleteDuplicates2(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}
	next := head.Next
	if head.Val == next.Val {
		for next != nil && head.Val == next.Val {
			next = next.Next
		}
		return deleteDuplicates2(next)
	} else {
		head.Next = deleteDuplicates2(head.Next)
		return head
	}
}

java

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode next = head.next;
        if (head.val == next.val) {
            while (next != null && head.val == next.val)
                next = next.next;
            return deleteDuplicates(next);
        } else {
            head.next = deleteDuplicates(head.next);
            return head;
        }
    }
}