232. 用栈实现队列
要求: 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x)将元素 x 推到队列的末尾int pop()从队列的开头移除并返回元素int peek()返回队列开头的元素boolean empty()如果队列为空,返回true;否则,返回false
思路
本题用两个栈实现队列(JS中用数组表示),主要难点在pop方法,我们会先看stackOut数组中是否还有数字,没有的话就把stackIn数组中剩余的数字放入stackOut中,再进行pop操作。
var MyQueue = function() {
this.stackIn = []
this.stackOut = []
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.stackIn.push(x)
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
if(this.stackOut.length != 0){
return this.stackOut.pop()
}else{
while(this.stackIn.length){
this.stackOut.push(this.stackIn.pop())
}
return this.stackOut.pop()
}
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
let x = this.pop()
this.stackOut.push(x)
return x
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
if(this.stackOut.length == 0 && this.stackIn.length == 0){
return true
}
return false
};
/**
* 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()
*/
225. 用队列实现栈
要求:请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x)将元素 x 压入栈顶。int pop()移除并返回栈顶元素。int top()返回栈顶元素。boolean empty()如果栈是空的,返回true;否则,返回false。
思路
本题用两个队列实现栈,利用队列先入先出的特征,用到数组中push和shift两个方法,定义栈的pop方法时,先将queue1前面的数字(size-1)个放到queue2中,在shift()出最新放入的数字,然后再将queue2中的内容复制给queue1;此题也可以只使用一个队列,即每次放入queue2的数字直接push放入queue1中,不需要另一个队列。
var MyStack = function() {
this.queue1 = []
this.queue2 = []
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue1.push(x)
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
let size = this.queue1.length
size--
while(size--){
this.queue2.push(this.queue1.shift())
}
let tmp = this.queue1.shift() //获取最后一个放入queue1的值
this.queue1 = this.queue2
this.queue2 = [] //清空第二个队列
return tmp
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
let tmp = this.queue1.pop()
this.queue1.push(tmp)
return tmp
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
while(this.queue1.length == 0){
return true
}
return false
};
/**
* 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()
*/