题目
- 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
- leetcode链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/submissions/
思想
- 队列,unshift
- 递归
- 栈,入栈后翻转
// 递归
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {number[]}
*/
var deepOrder = (array, node) => {
if (node) {
deepOrder(array, node.next)
array.push(node.val)
}
};
var reversePrint = function(head) {
const list = []
deepOrder(list, head)
return list
};
// 队列
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {number[]}
*/
var reversePrint = function(head) {
const result = []
while(head) {
result.unshift(head.val)
head = head.next
}
return result
};
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {number[]}
*/
var reverse = (array) => {
let x = 0
let y = array.length - 1
while(x <= y) {
[array[x], array[y]] = [array[y], array[x]]
x++
y--
}
};
var reversePrint = function(head) {
const stack = []
while(head) {
stack.push(head.val)
head = head.next
}
reverse(stack)
return stack
};