面试题7:用两个栈实现队列

剑指Offer面试题7:用两个栈是实现队列(JS实现)

题目描述::用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deletedHead,分别完成在队列尾部插入节点和在队列头部删除节点的功能。

    //栈
    function Stack(){
        var items = [];
        this.push = function(element){
            items.push(element);
        }
        this.pop = function(){
            return items.pop();
        }
        //返回栈顶元素
        this.peek = function(){
            return items[items.length-1];
        }
        this.isEmpty = function(){
            return items.length === 0;
        }
        this.size = function(){
            return items.length;
        }
        this.clear = function(){
            items = [];
        }
        this.print = function(){
            console.log(items.toString());
        }
    }


    //用两个栈实现队列
    function Queue() {
        var stack1 = new Stack();
        var stack2 = new Stack();
        //向队列的尾部添加元素
        this.appendTail = function(element) {
            stack1.push(element);
        }
        //从队列头部移除元素
        this.deleteHead = function() {
            if(stack2.size() <= 0) {
                while(stack1.size() > 0) {
                    stack2.push(stack1.pop());
                }
                if(stack2.size() === 0) {
                    return false;
                }
            }
            return stack2.pop();
        }
    }

    var queue = new Queue();
    queue.appendTail(5);
    queue.appendTail(8);
    queue.appendTail(15);
    queue.appendTail(2);
    queue.appendTail(9);
    console.log(queue.deleteHead());
    queue.appendTail(100);
    console.log(queue.deleteHead());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值