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从尾到头打印链表

猜你喜欢

转载自blog.csdn.net/qq_38970408/article/details/122210688