剑指offer--3.从头打印链表

时间:2022-01-05 17:12:45

题目:输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

思路:可以利用push 和unshift

/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function printListFromTailToHead(head)
{
var res = [];
while(head) {
res.push(head.val);
head = head.next;
}
return res.reverse();
}
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function printListFromTailToHead(head)
{
var res = [];
while(head) {
res.unshift(head.val);
head = head.next;
}
return res;
}