思路: 在压栈的时候做处理。队列是先进先出,而栈是先进后出。因此每次入栈,都要先压入队列。然后把队列出了最后一个元素,其他元素都出队列,再进队列。也可以用双队列实现。
代码:
queue<int> que;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que.push(x);
for(int i=0;i<que.size()-1;i++){
que.push(que.front());
que.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int res=que.front();
que.pop();
return res;
}
/** Get the top element. */
int top() {
return que.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return que.empty();
}