每日一题 [9]-用栈实现队列

2017-03-01  本文已影响0人  MAXPUP

题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解:
队列:先进先出
栈:后进先出
首先定义栈:

function Stack(){
  var item = [];
  this.push = function(node){
    item.push(node);
    return item;
  }
  this.pop = function(){
    return item.pop();
  }
  this.isEmpty = function(){
    return item.length ===0;
  }
}

然后就是队列的方法,push只需要把值放入栈中就好

function push(node)
{
    stack1.push(node);
}

因为栈出的顺序和队列是相反的,所以需要先弹出放入另外一个栈中,这个栈pop的顺序就和队列一样了。

function pop()
{
    if(stack1.isEmpty() && stack2.isEmpty()){
        throw new Error("空队列");
    }
    if(stack2.isEmpty()){
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
    }
    return stack2.pop();
}
上一篇 下一篇

猜你喜欢

热点阅读