232. Implement Queue using Stacks
难度简单749收藏分享切换为中文接收动态反馈
Queue 像是人在排队 先来的先走 FIFO 对应数组的 push shift方法即可
简单利用push shift实现Queue队列数据结构
- Queue.push => arr.push
- Queue.push => arr.shift
- Queue.push => arr[0]
- Queue.empty => !arr.length
代码
var MyQueue = function() {
this.queue = []
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.queue.push(x)
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
return this.queue.shift()
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
return this.queue[0]
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return !this.queue.length
};
/**
* 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()
*/
利用双栈实现的解题思路
- 通过 class constructor 实现 Stack 栈数据结构 FILO push pop, empty: 是否存在元素,last 返回最有一个元素
- 双栈一个 input 维护进栈的元素,一个 output 维护出栈的元素
- 当 MyQueue.push 时直接 input.push
- 当 MyQueue.pop 时,需要判断 output栈中是否为空即拍好队的元素是否为空,调用 output.empty()去判断, 如果output 为空则直接调用 in2out,即将 input 所有元素 弹出 pop, output压栈push input弹出 (pop)的元素,这样就将 input倒置了那么最后一个元素就是 MyQueue的第一个元素即 peek
代码
// FILO push pop
class Stack {
constructor() {
this.stack = []
}
push(x) {
this.stack.push(x)
}
pop() {
return this.stack.pop()
}
empty() {
return !this.stack.length
}
last() {
return this.stack[this.stack.length - 1]
}
}
var MyQueue = function () {
this.input = new Stack()
this.output = new Stack()
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function (x) {
this.input.push(x)
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function () {
this.peek()
return this.output.pop()
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function () {
if(this.output.empty()) {
this.in2out()
}
return this.output.last()
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
return this.input.empty() && this.output.empty()
};
MyQueue.prototype.in2out = function () {
while (!this.input.empty()) {
this.output.push(this.input.pop())
}
};
/**
* 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()
*/