剑指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());