用队列实现栈
程序员文章站
2022-03-30 07:58:59
...
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
queue<int> tmp_queue;//临时队列,用于辅助调换数据队列的元素顺序
tmp_queue.push(x);
while(data_queue.size())//假设data队列的数据:back 1 2 3 4 front,tmp队列是 5
{
tmp_queue.push(data_queue.front());//tmp队列就成了:back 4 5 front,data是:1 2 3
data_queue.pop();
}//tmp队列就成了:back 1 2 3 4 5 front
while(tmp_queue.size())
{
data_queue.push(tmp_queue.front());
tmp_queue.pop();
}//data队列就成了:back 1 2 3 4 5 front, 5是最后进的,根据栈,5也该是先出的
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int x = data_queue.front();
data_queue.pop();
return x;
}
/** Get the top element. */
int top() {
return data_queue.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return data_queue.empty();
}
private:
queue<int> data_queue;//实现栈的队列
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* bool param_4 = obj.empty();
*/