1.题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。(也就是操作这两个“先进后出”的栈实现一个“先进先出”的队列)
2.题目分析
栈是先进后出,队列是先进先出,因此两个栈,一个用来push,一个用来pop,同时注意下两个栈不为空的时候。
思路:
入队:将元素进栈1;
出队:判断栈2是否为空,如果为空,则将栈1中所有元素pop,并push进栈2,栈2出栈; 如果不为空,栈2直接出栈。
3.代码
var stack1 = [];
var stack2 = [];
function push(node){
stack1.push(node);
}
function pop(){
if(stack2.length == 0){
while(stack1.length > 0){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
完整版代码:
function Stack(){
var item = [];
this.push = function (node){
item.push(node);
};
this.pop = function (){
return item.pop();
}
this.isEmpty = function (){
return item.length===0;
}
}
var stack1 = new Stack();
var stack2 = new Stack();
function push(node)
{
stack1.push(node);
}
function pop()
{
if(stack1.isEmpty() && stack2.isEmpty()){
throw new Error("Queue is empty");
}
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
参考文章:
https://www.cnblogs.com/wuguanglin/p/pushAndPop.html
https://www.cnblogs.com/echovic/p/6430640.html
https://wenhuiyang-luck.github.io/2017/07/24/《剑指offer》— JavaScript(5)用两个栈实现队列/