Skip to main content

从尾到头打印链表

06. 从尾到头打印链表

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

示例

输入:head = [1,3,2] 输出:[2,3,1]

代码

思路:

  1. 防御性
  2. while 遍历链表存入数组
  3. 数组反转并返回
var reversePrint = function (head) {
if (!head) return []

const arr = []
while (head) {
arr.push(head.val)
head = head.next
}
return arr.reverse()
}

链接

参考链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/js-3chong-jie-ti-by-rinnyushinndesu/