title | description | keywords | ||||||
---|---|---|---|---|---|---|---|---|
83. 删除排序链表中的重复元素 |
LeetCode 83. 删除排序链表中的重复元素题解,Remove Duplicates from Sorted List,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。 |
|
Given the head
of a sorted linked list, delete all duplicates such that
each element appears only once. Return the linked list sorted as well.
Example 1:
Input: head = [1,1,2]
Output: [1,2]
Example 2:
Input: head = [1,1,2,3,3]
Output: [1,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 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;
}
} else {
prev = prev.next;
}
}
return res.next;
};
题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
---|---|---|---|---|---|
82 | 删除排序链表中的重复元素 II | [✓] | 链表 双指针 |
🟠 | 🀄️ 🔗 |
1836 | 从未排序的链表中移除重复元素 🔒 | 哈希表 链表 |
🟠 | 🀄️ 🔗 |