面试题 02.01. 移除重复节点
小于 1 分钟
面试题 02.01. 移除重复节点
/**
* 编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
* 示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
*/
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function removeDuplicateNodes(head: ListNode | null): ListNode | null {
let hashMap: Map<number, string> = new Map();
let current = head; // 遍历用
let p = head as ListNode; // 头
while (current) {
if (hashMap.has(current.val)) {
// 已存在
p.next = current.next;
} else {
// 不存在时
p = current;
hashMap.set(current.val, "c");
}
current = current.next;
}
return head;
}
class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
let listTag1 = new ListNode(1);
let listTag2 = new ListNode(2);
let listTag3 = new ListNode(3);
let listTag4 = new ListNode(3);
let listTag5 = new ListNode(2);
let listTag6 = new ListNode(1);
listTag1.next = listTag2;
listTag2.next = listTag3;
listTag3.next = listTag4;
listTag4.next = listTag5;
listTag5.next = listTag6;
console.log(removeDuplicateNodes(listTag1));
Loading...
