《剑指offer》--01.从尾到头打印链表--JavaScript

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
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值