class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size();
size--;
while (size--) {
if (!que.empty()) {
que.push(que.front());
que.pop();
}
}
int res = que.front();
que.pop();
return res;
}
int top() {
int res = this->pop();
que.push(res);
return res;
}
bool empty() {
return que.empty();
}
};
/**
* 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();
*/
思路:本来应该用两个队列来操作,但是用一个队列其实思路一样,相当于每次找到最后放进去的元素,就是在一个队列里面不断把最后放进去的元素往前推的感觉,其他元素的相对位置不变,而最后放进去的元素已经被推倒第一个输出的位置了。