class MyStack {
public:
// 用两个队模拟栈
queue<int> que1;
queue<int> que2; // 辅助队列,备份用
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
// error: no member named 'top'
// error: no member named 'peek'
// error: cannot initialize a variable of type 'int' with an rvalue of type 'void'
// queue 可以使用 front() 和 back()
int pop() {
int size = que1.size();
size--;
while (size--) {
que2.push(que1.front());
que1.pop();
}
int result = que1.front();
que1.pop();
// 再将 que2 赋值给 que1
que1 = que2;
// 清空 que2
while(!que2.empty()) {
que2.pop();
}
return result;
}
/** Get the top element. */
int top() {
return que1.back();
}
/** Returns whether the stack is empty. */
bool empty() {
return que1.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();
*/
总结
- 定义queue<…> x
- 两个队列,其中 一个用来备份的队列
- error: no member named ‘top’
- error: no member named ‘peek’
- error: cannot initialize a variable of type ‘int’ with an rvalue of type ‘void’
- queue 可以使用 front() 和 back()