# 剑指06.从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入:head = [1,3,2]
输出:[2,3,1]
1
2
2
# 解答
reverse()
var reversePrint = function (head) {
if (head === null) return []
const res = []
while (head) {
res.push(head.val)
head = head.next
}
return res.reverse()
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
- 反转链表
// 首先将链表反转
function reverseLink(head) {
if (head === null || head.next === null) return head
let p = head.next
head.next = null
let tmp = null
while (p !== null) {
tmp = p.next // tmp 指针前进(保存下一个指针信息)
p.next = head // 指针反转
head = p // head 指针前进
p = tmp // p 指针前进
}
return head
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
- 递归反转链表
function reverseLink(head) {
if (head === null || head.next === null) return head
const p = reverseLink(head.next)
head.next.next = head // 指针反转
head.next = null
return p // 返回真正的表头
}
1
2
3
4
5
6
7
2
3
4
5
6
7