JS从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

  • 示例 :

输入:head = [1,3,2]
输出:[2,3,1]
限制:0 <= 链表长度 <= 10000

  • 解题思路:

1.利用栈
遍历链表,遍历的顺序是从头到尾,可输出的顺序却是从尾到头;也就是说第一个遍历到的节点最后一个输出,而最后一个遍历到的节点第一个输出。这个就是典型的后进先出,我们可以用栈来实现这种顺序,每经过一个节点的时候,把该节点放到一个栈中,当遍历完整个链表后,再从栈顶开始依次输出节点的值
2.利用递归
既然想到了用栈,而递归本质上就是一个栈结构,要实现反过来输出链表,每访问到一个节点的时候,先递归输出它后面的节点,再输出该节点自身,这样链表的输出结果就反过来了
3.unshift() / reverse()
遍历链表、将每个元素从数组头部插入、实现倒序输出

方法一:利用栈

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {number[]}
 */
var reversePrint = function(head) {
    var nodes=[];
    while(head!=null){
       nodes.push(head.val);
       head=head.next;
    }
    let result=[];
    let temp = nodes.pop();
    while (temp != null) {
        result.push(temp);
        temp = nodes.pop();
    }
    return result;
};

方法二:利用递归

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {number[]}
 */
var reversePrint = function(head, arr = []) {  
  // 利用函数递归栈的特性
  if (head != null) {
    if (head.next != null) {
      reversePrint(head.next, arr);
    }
    arr.push(head.val);
  }
  return arr;
};

方法三:利用JS的reverse()或unshift()方法

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {number[]}
 */
var reversePrint = function(head) {
     var nodes=[];
     while(head!=null){
       nodes.push(head.val);
       head=head.next;
     }
    return nodes.reverse();
}
//或
var reversePrint = function(head) {
     var nodes=[];
     while(head!=null){
       nodes.unshift(head.val);
       head=head.next;
     }
    return nodes;
}

注:unshift() 方法将新项添加到数组的开头,并返回新的长度。

简书同文欢迎关注 JS从尾到头打印链表

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值