01.从尾到头打印链表
题目
题解1
利用unshift方法的特点,在数组最前面插入元素,可以使得数组倒序。
先遍历链表,将链表中的每一个值插入到新创建的元素的开头,从而达到题目要求的数组是从尾到头的顺序。
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function printListFromTailToHead(head)
{
const res = []
while(head){
res.unshift(head.val)
head = head.next
}
return res
}
module.exports = {
printListFromTailToHead : printListFromTailToHead
};
题解2
首先,题目要求得到的数组从尾到头的顺序,可以想到数据结构栈的特点【后进先出】。
利用这个特点来达到要求。先遍历链表中的值将它们push进数组中,然后利用pop得到最终结果。
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function printListFromTailToHead(head)
{
const res = []
while(head){
res.push(head.val)
head = head.next
}
const rev = []
while(res.length){
rev.push(res.pop())
}
return rev
}
module.exports = {
printListFromTailToHead : printListFromTailToHead
};
题解3
在题解2基础上,利用数组方法reverse。
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function printListFromTailToHead(head)
{
const res = []
while(head){
res.push(head.val)
head = head.next
}
return res.reverse()
}
module.exports = {
printListFromTailToHead : printListFromTailToHead
};