- 思路
一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时在去弹出元素就是栈的顺序了。
class MyStack
{
public:
queue<int> que;
/** Initialize your data structure here. */
MyStack()
{
}
/** Push element x onto stack. */
void push(int x) //直接将元素push进队列
{
que.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop()
{
int size = que.size();
size--;//确保最后一个元素不被添加到队尾
while (size--)
{
que.push(que.front());// 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
que.pop();
}
int res = que.front(); // 此时弹出的元素顺序就是栈的顺序了
que.pop();
return res;
}
/** Get the top element. */
int top()
{
return que.back();
}
/** Returns whether the stack is empty. */
bool empty()
{
return que.empty();
}
};