什么是栈?
栈是一种严格遵循先进后出,后进先出的数据格式;
什么是队列?
栈是一种严格遵循先进先出,后进后出的数据格式;
那么如何化栈为队?
利用两个栈,负负得正;
大概逻辑:
一个栈为inStack表示push()的栈,一个为outStack表示pop()的栈;
push:
直接将元素推入inStack中,inStack.push();
pop:
- 判断两个栈是否为空,为空就返回false;
- 如果outStack.length存在那么就返回 outStack最后一个元素;
peek:
- 如果没有值直接返回false;
- 如果outStack.length存在,那么outStack中的有值肯定是最先进来的,且outStack最先进来的应该是outStack[outStack.length-1],返回outStack[outStack.length-1]
- 如果outStack.length不存在,那么inStack[0]就为最先进来的返回inStack[0]
emty:
instack.length 和 outStack.length都等于 0 那么说明队列为空
/**
* Initialize your data structure here.
*/
var MyQueue = function() {
this.inStack = [];
this.outStack = [];
};
/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.inStack.push(x);
};
/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/
MyQueue.prototype.pop = function() {
if(this.empty()){
return false;
}
if(this.outStack.length!==0){
return this.outStack.pop();
}else{
let length = this.inStack.length;
while(length>0){
this.outStack.push(this.inStack.pop());
length--;
}
return this.outStack.pop();
}
};
/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function() {
if(this.empty()){
return false;
}
if(this.outStack.length){
return this.outStack[this.outStack.length - 1];
}
return this.inStack[0]
};
/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return this.inStack.length + this.outStack.length === 0;
};
/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/