[LeetCode] 82. Remove Duplicates from Sorted List II
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Example 1: Input: head = [1,2,3,3,4,4,5] Output: [1,2,5]
Example 2: Input: head = [1,1,1,2,3] Output: [2,3]
Constraints: The number of nodes in the list is in the range [0, 300]. -100 <= Node.val <= 100 The list is guaranteed to be sorted in ascending order.
删除排序链表中的重复元素II。
给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
思路
题意跟版本一很接近,唯一的区别是,版本一是请你删除重复元素,使得 output 里面每个元素只出现一次。版本二是请你删除所有出现超过一次的元素。思路是需要创建一个 dummy 节点,放在所有需要遍历的节点之前,遍历的时候,找是否有两个节点的 val 相同,找到后记下这个 val。再往后遍历的时候,只要遇到这个 val 就跳过。