82. Remove Duplicates from Sorted List II
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.
题目大意
删除链表中重复的结点,只要是有重复过的结点,全部删除。
解题思路
按照题意做即可。
代码
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function (head) {
let obj = {};
let res = new ListNode(0, head);
let prev = res;
while (prev.next && prev.next.next) {
if (prev.next.val === prev.next.next.val) {
// 删除与 prev.next 重复的节点
while (
prev.next &&
prev.next.next &&
prev.next.val === prev.next.next.val
) {
prev.next = prev.next.next;
}
// 删除 prev.next 节点
prev.next = prev.next.next;
} else {
prev = prev.next;
}
}
return res.next;
};
相关题目
相关题目
- [83. 删除排序链表中的重复元素](./0083.md)
- [🔒 Remove Duplicates From an Unsorted Linked List](https://leetcode.com/problems/remove-duplicates-from-an-unsorted-linked-list)