Chipmunk & Panda

-- 鼠熊部落格

All work and no play makes Jack a dull boy.

从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof

初见

甚至一下子没反应过来……遍历链表,存储数值,反向打印就可以了。正经是用到栈(从头到尾压栈,出栈时就是从尾到头了), 但因为题目要求只是直接返回一个数组而不是真的一个个打印出来,所以取巧直接用 unshift() 把数值依次插入到队首就可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
function ListNode(val) {
this.val = val;
this.next = null;
}
*/

var reversePrint = function (head) {
let result = []
while (head) {
result.unshift(head.val)
head = head.next
}
};

递归解法

感觉没必要……

1
2
3
4
5
6
7
8
9
10
function reversePrint(head) {
if (head == null) return []
return [...reversePrint(head.next), head.val]
}

/*
作者:simonwong
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/di-gui-by-simonwong-kwkl/
来源:力扣(LeetCode)
*/