创建链表
function ListNode(val, next) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
function arrayToLinkedList(arr) {
if (arr.length === 0) return null;
let head = new ListNode(arr[0]);
let current = head;
for (let i = 1; i < arr.length; i++) {
current.next = new ListNode(arr[i]);
current = current.next;
}
return head;
}
const arr = [1, 2, 3, 4, 5];
const linkedList = arrayToLinkedList(arr);
console.log(JSON.stringify(linkedList, null, 2));
1 -> 2 -> 3 -> 4 -> 5 -> null
{
"val": 1,
"next": {
"val": 2,
"next": {
"val": 3,
"next": {
"val": 4,
"next": {
"val": 5,
"next": null
}
}
}
}
}
遍历链表
function traverseLinkedList(head) {
let current = head;
while (current !== null) {
console.log(current.val);
current = current.next;
}
}
let arr = [1, 2, 3, 4, 5];
let linkedList = arrayToLinkedList(arr);
traverseLinkedList(linkedList);