algorighm/leetcode/简单/删除排序链表中的重复元素.js

70 lines
1.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
83. 删除排序链表中的重复元素
简单
相关标签
相关企业
给定一个已排序的链表的头 head 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
示例 1
输入head = [1,1,2]
输出:[1,2]
示例 2
输入head = [1,1,2,3,3]
输出:[1,2,3]
提示:
链表中节点数目在范围 [0, 300] 内
-100 <= Node.val <= 100
题目数据保证链表已经按升序 排列
*/
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
import { LinkListNode as ListNode } from '../../list/index.js';
const deleteDuplicates = function (head) {
let left = head;
let right = head;
while (right) {
if (left.val === right.val) {
right = right.next;
} else {
left.next = right;
left = right;
}
}
left.next = right;
};
// 示例链表1 -> 2 -> 3 -> 4 -> 5
const node1 = new ListNode(1);
const node2 = new ListNode(2);
const node3 = new ListNode(2);
const node4 = new ListNode(2);
const node5 = new ListNode(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
// 删除重复元素
deleteDuplicates(node1);
// 打印反转后的链表
let current = node1;
while (current !== null) {
console.log(current.val);
current = current.next;
}