# 题目描述
输入一个链表,按链表从尾到头的顺序返回一个 Array
# 测试用例
用例:
- 输入:
[ 1, 2, 3, 4, 5 ]
- 输出:
[ 5, 4, 3, 2, 1 ]
# 思路
遍历链表,通过unshift
方法往数组的头部插入
# 代码实现
// 输入
var __readline = require("readline-sync");
__readline.setDefaultOptions({ prompt: "" });
var readline = __readline.prompt;
// 链表数据结构
function ListNode(val, next) {
this.val = val == undefined ? 0 : val;
this.next = next == undefined ? null : next;
}
// 输入链表
console.log("请输入链表: ");
let arr = readline().split(",").map(Number);
console.log("链表的数组表示形式为: ", arr);
// 把输入的数组形式转化为链表
let dummyHead = new ListNode();
let p = dummyHead;
for(let i = 0; i < arr.length; i ++){
p.next = new ListNode(arr[i]);
p = p.next;
}
console.log("dummyHead: ", dummyHead.next);
// 从头到尾打印链表
function tailToHead (head){
let res = [];
let cur = head;
while(cur != null){
res.unshift(cur.val);
cur = cur.next;
}
return res;
}
let res = tailToHead(dummyHead.next);
console.log("结果为: ", res);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43