数据处理 | 链表数组互转

链表转数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function nodeList2Array(head) {
let array = [];
while (head) {
array.push(head.val);
head = head.next;
};
return array;
}

// test
// 设置一个链表 1-> 2 -> 3 -> 4 -> 5
const head = { val: 1, next: { val: 2, next: { val: 3, next: { val: 4, next: { val: 5, next: null}}}}};
const array = nodeList2Array(head);
console.log(array); // [ 1, 2, 3, 4, 5 ]

数组转链表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function NodeList(val, next) {
this.val = val ? val : undefined;
this.next = next ? next : null;
}

function array2NodeList(array) {
if (!array.length) return null;
let dum = new NodeList(-1, null);
let newHead = dum;
while (array.length) {
let node = array.shift();
newHead.next = {
val: node,
next: null,
};
newHead = newHead.next;
};
return dum.next;
}

// test
const array = [ 1, 2, 3, 4, 5 ];
const head = array2NodeList(array);
console.log(head);