实现一个MyQueue类,该类用两个栈来实现一个队列。 说明:
你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的。 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
解题思路
首先先设置两个栈
| | | |
| | | |
| | | |
| | | |
|____| |____|
pushStack popStack
本着队列的性质,先进先出原则
- push时,需要将放到队列尾部 因为popStack还有值,需要先将popStack清空,x才能插到队列的尾部
|——------| <---- x
| | | | | |
| | | | | |
| \/ | | | |
| a | | b |
|____| |____|
pushStack popStack
|-——--------- x
| \/ | | |
| x | | |
| b | | |
| a | | |
|____| |____|
pushStack popStack
- pop时,需要将队首的值删(还是再强调:栈是后进先出的) 因为栈是后进先出的,所以需要将pushStack的栈一个个取出来放到popStack中,然后删除popStack中的最后一个元素
|---------|
| | | | | |
| | | | | |
| b | | \/ |
| a | | c |
|____| |____|
pushStack popStack
|---------|
| | | | | |
| | | | \/ |
| | | | b |
| a | | c |
|____| |____|
pushStack popStack
| | | |
| | | a |
| | | b |
| | | c |
|____| |____|
pushStack popStack
- peek时,取的是队列队首的值 因为是栈的关系,所以我们还是要将pushStack的栈一个个取出来当道popStack中,然后取popStack中的最后一个元素
| | | |
| | | a | <-- 队首
| | | b |
| | | c |
|____| |____|
pushStack popStack
- empty时,也就是两个栈表都为空,因为上面操作,只有在两个栈长度都为0的情况下(也就是相等),队列为空
代码
/**
* Initialize your data structure here.
*/
var MyQueue = function() {
this.pushStack = [];
this.popStack = [];
};
/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
while(this.popStack.length > 0) {
this.pushStack.push(this.popStack.pop())
}
this.pushStack.push(x)
};
/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/
MyQueue.prototype.pop = function() {
while(this.pushStack.length > 0) {
this.popStack.push(this.pushStack.pop())
}
return this.popStack.pop()
};
/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function() {
while(this.pushStack.length > 0) {
this.popStack.push(this.pushStack.pop())
}
return this.popStack[this.popStack.length - 1]
};
/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return this.pushStack.length == this.popStack.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()
*/