translate arrToLinkedList method

This commit is contained in:
steak-zhuo 2023-01-08 12:47:33 +08:00
parent 01b95bc0f9
commit a7a3618ee0
2 changed files with 30 additions and 11 deletions

View File

@ -4,6 +4,10 @@
* Author: zhuoqinyue (1403450829@qq.com)
*/
import { printLinkedList } from "../module/PrintUtil";
import ListNode from "../module/ListNode";
/* 哈希查找(数组) */
function hashingSearch(map: Map<number, number>, target: number) {
// 哈希表的 key: 目标元素value: 索引
@ -31,17 +35,17 @@ function main() {
const index = hashingSearch(map, target);
console.log("目标元素 3 的索引 = " + index);
// /* 哈希查找(链表) */
// let head = new ListNode().arrToLinkedList(nums)
// // 初始化哈希表
// const map1 = new Map();
// while (head != null) {
// map1.set(head.val, head); // key: 结点值value: 结点
// head = head.next;
// }
// const node = hashingSearch1(map1, target);
// console.log("目标结点值 3 的对应结点对象为" );
// printLinkedList(node);
/* 哈希查找(链表) */
let head = new ListNode().arrToLinkedList(nums)
// 初始化哈希表
const map1 = new Map();
while (head != null) {
map1.set(head.val, head); // key: 结点值value: 结点
head = head.next;
}
const node = hashingSearch1(map1, target);
console.log("目标结点值 3 的对应结点对象为");
printLinkedList(node);
}
main();

View File

@ -14,4 +14,19 @@ export default class ListNode {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
/**
* Generate a linked list with an array
* @param arr
* @return
*/
arrToLinkedList(arr: number[]) {
const dum: ListNode = new ListNode(0);
let head = dum;
for (const val of arr) {
head.next = new ListNode(val);
head = head.next;
}
return dum.next;
}
}