js中如何构造链表
js中本身没有链表数据结构,所以我们需要手动构造下。
//数据结构
export class ListNode {
constructor(val = 0, next = null) {
this.val = val;
this.next = next;
}
}
// 数组转链表
export function createLinkedList(values) {
if (!values || values.length === 0) {
return null;
}
let head = new ListNode(values[0]);
let current = head;
for (let i = 1; i < values.length; i++) {
current.next = new ListNode(values[i]);
current = current.next;
}
return head;
}
// 链表转数组
export function printLinkedList(head){
let current = head
let values = []
while(current !== null){
values.push(current.val)
current = current.next;
}
console.log(values)
}
根据上面的代码你就构造了在js中可以自由转换的链表数据了,然后我的建议是Leetcode刷两道题,这样你就基本上对链表有一个初步的了解了; 链表这种数据结构在日常的业务开发过程中基本上没有应用的地方,所以我认为了解到这种地步就ok了。
合并两个有序链表 leetcode.cn/problems/me…