5.栈实现队列

218 阅读1分钟

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。


思路

栈是先进后出(FILO),队列是先进先出(FIFO);

用两个栈实现队列,push方法没有区别,pop方法要弹出栈底;

因此用 pop 方法时要把栈翻转。


代码

function ListNode(x){
    this.val = x;
    this.next = null;
}
function printListFromTailToHead(head)
{
    let ret = [];
    let pNode = head;
    
    while (pNode !== null) {
        ret.unshift(pNode.val);
        pNode = pNode.next;
    }
    return ret;
}