| title | 82. 删除排序链表中的重复元素 II | |||||||
|---|---|---|---|---|---|---|---|---|
| description | LeetCode 82. 删除排序链表中的重复元素 II题解,Remove Duplicates from Sorted List II,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。 | |||||||
| keywords |
|
🟠 Medium 🔖 链表 双指针 🔗 力扣 LeetCode
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.
给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
按照题意做即可。
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function (head) {
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 | 删除排序链表中的重复元素 | [✓] | 链表 |
🟢 | 🀄️ 🔗 |
| 1836 | 从未排序的链表中移除重复元素 🔒 | 哈希表 链表 |
🟠 | 🀄️ 🔗 |

