用兩個棧實現(xiàn)隊列
題目描述
用兩個棧來實現(xiàn)一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。
代碼如下:
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);
// write code here
}
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();
// write code here
}
module.exports = {
push : push,
pop : pop
};
解題思路
棧是一種后進先出的數(shù)據(jù)結(jié)構(gòu),而隊列是一種先進先出的數(shù)據(jù)結(jié)構(gòu),那么本題中,
1、實現(xiàn)入隊:將元素直接壓入棧1。
2、實現(xiàn)出隊:先判斷兩個棧是否都為空,如果不是,在判斷棧2,如果為空,棧1不為空,先將棧1的元素全部出棧,按順序壓入棧2,然后再從棧2中出棧,就取得了原來在棧1棧底的元素了。