题目:
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push
、top
、pop
和 empty
)。
实现 MyStack
类:
void push(int x)
将元素 x 压入栈顶。int pop()
移除并返回栈顶元素。int top()
返回栈顶元素。boolean empty()
如果栈是空的,返回true
;否则,返回false
。
进阶版用一个队列实现栈
队列: 先进先出
栈:先进后出
关系: 入栈与入队列没有区别 出栈与出队列是不同的
- 把队列的最后一个元素作为第一个元素出栈 (这样二者就一样了)
var MyStack = function() {
this.queue=[];
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue.push(x);
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
let ans = this.queue.pop();
return ans;
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
return this.queue.slice(-1)[0]; //slice()通过索引位置获取新的数组,该方法不会修改原数组,只是返回一个新的子数组。
//this.queue.slice(-1) 返回的是数组最后一个元素 格式为 [x]
//this.queue.slice(-1)[0] 取下标为0的元素
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return !this.queue.length;
};
/**
* Your MyStack object will be instantiated and called as such:
* var obj = new MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/
普通版:用两个队列实现
思路:主队列 queue 备用队列 _queue
- 入栈与入队列都是一样的
- 出栈与出队列是不同的 把所有元素添加到queue中 从头拿出this.queue.length-1个元素(留一个元素在queue中 这个元素就是要删除的元素) 放在备用队列_queue中保存 待删除主队列queue中的唯一元素时,在全部把备用队列的元素,放回主队列中
- 备用队列就是一个临时空间 , 保存主队列元素的作用
var MyStack = function() {
this.queue=[];
this._queue=[];
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue.push(x);
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
while(this.queue.length>1){
this._queue.push(this.queue.shift())
}
ans = this.queue.shift()
while(this._queue.length){
this.queue.push(this._queue.shift())
}
return ans
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
return this.queue.slice(-1)[0];
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return !this.queue.length;
};
/**
* Your MyStack object will be instantiated and called as such:
* var obj = new MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/