From a7a3618ee0ca708d6653d491bc5fff49256dba3c Mon Sep 17 00:00:00 2001 From: steak-zhuo Date: Sun, 8 Jan 2023 12:47:33 +0800 Subject: [PATCH] translate arrToLinkedList method --- .../chapter_searching/hashing_search.ts | 26 +++++++++++-------- codes/typescript/module/ListNode.ts | 15 +++++++++++ 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/codes/typescript/chapter_searching/hashing_search.ts b/codes/typescript/chapter_searching/hashing_search.ts index 0d89ee9c..d0ab8bb5 100644 --- a/codes/typescript/chapter_searching/hashing_search.ts +++ b/codes/typescript/chapter_searching/hashing_search.ts @@ -4,6 +4,10 @@ * Author: zhuoqinyue (1403450829@qq.com) */ +import { printLinkedList } from "../module/PrintUtil"; +import ListNode from "../module/ListNode"; + + /* 哈希查找(数组) */ function hashingSearch(map: Map, 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(); diff --git a/codes/typescript/module/ListNode.ts b/codes/typescript/module/ListNode.ts index d6d60616..a5e30340 100644 --- a/codes/typescript/module/ListNode.ts +++ b/codes/typescript/module/ListNode.ts @@ -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; + } }