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

来源:互联网 发布:java中的同步 编辑:程序博客网 时间:2024/06/15 20:27

剑指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());
0 0
原创粉丝点击