题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
题解:
- 方法一:将链表存入一个数组之中,然后进行数组的反转。
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function printListFromTailToHead(head)
{
// write code here
let stack = [];
while(head){
stack.push(head.val);
head = head.next;
}
return stack.reverse();
}
- 方法二:跟上面大同小异。
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function printListFromTailToHead(head)
{
// write code here
let arr = [];
while(head){
arr.unshift(head.val);
head = head.next;
}
return arr;
}