《剑指Offer》JavaScript实战——从尾到头打印链表

题目描述

    输入一个链表,从尾到头打印链表每个节点的值。
解题方法
/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function printListFromTailToHead(head)
{
    // write code here
    /* 栈的思想,不过好像实现的比较畸形,哈哈 */
    let array = [],
        arr=[];
    while(head != null){
        array.push(head.val);
        head = head.next;
    }
    while(array.length){
        arr.push(array.pop());
    }
    return arr;
    
    
    /* 使用unshift的方式,最快速,不然还得两遍循环 */
    let array = [];
    while(head != null){
        array.unshift(head.val);
        head = head.next;
    }
    return array;
}

猜你喜欢

转载自blog.csdn.net/sinat_36521655/article/details/80581719
今日推荐