题目描述
原题链接:232. 用栈实现队列
使用两个对顶栈实现
因为只能用栈的后进先出的方式实现队列先进先出的方式,因此就使用两个栈来实现。
一个stack用于输入元素,另一个stack用于输出元素。
每次先输入的会被压入到stack-in的栈底,当想要实现队列的方式输出时,需要让stack-in的栈底元素输出。因此就再用另一个stack-out作为媒介,将stack-in中元素全部压入stack-out中,此时stack-in中的栈底元素,就变成了stack-out中的栈顶元素。此时输出stack-out中元素时,先被输出的便是stack-in中的栈底元素。从而实现了队里的FIFO操作方式。
C++版本
class MyQueue {
public:
stack<int> sIn;
stack<int> sOut;
MyQueue() {
}
void push(int x) {
sIn.push(x);
}
int pop() {
// 当sOut里为空时,将sIn中元素都加入压入进去
if(sOut.empty()) {
while(!sIn.empty()) {
sOut.push(sIn.top());
sIn.pop();
}
}
// 当sOut里不为空时,获取sOut的栈顶元素弹出
int res = sOut.top();
sOut.pop();
return res;
}
int peek() {
// 复用已定义过的pop()方法
int res = this->pop();
// 因为为获取队头元素,而不弹出,因此需要压回栈中
sOut.push(res);
return res;
}
bool empty() {
return sOut.empty() && sIn.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
Python版本
class MyQueue:
def __init__(self):
self.sIn = []
self.sOut = []
def push(self, x: int) -> None:
self.sIn.append(x)
def pop(self) -> int:
if not self.sOut:
while self.sIn:
self.sOut.append(self.sIn.pop())
return self.sOut.pop()
def peek(self) -> int:
res = self.pop()
self.sOut.append(res)
return res
def empty(self) -> bool:
return not self.sOut and not self.sIn
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
参考文章:232.用栈实现队列、用栈实现队列