feat: 删除链表中的重复元素(83)
This commit is contained in:
parent
0adc54836f
commit
887a6e48fe
69
leetcode/简单/删除排序链表中的重复元素.js
Normal file
69
leetcode/简单/删除排序链表中的重复元素.js
Normal file
@ -0,0 +1,69 @@
|
||||
/*
|
||||
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;
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user