用队列实现栈
Implement Stack using Queues
解
掌握栈(先进后出)和队列(先进先出)的特点,这题就很简单
class MyStack {
public:
/** Initialize your data structure here. */
queue<int> q;
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
queue<int>temp;
temp.push(x);
while (!q.empty()) {
temp.push(q.front());
q.pop();
}
q = temp;
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
if (q.empty()) {
return -1;
}
int ret = q.front();
q.pop();
return ret;
}
/** Get the top element. */
int top() {
if (q.empty()) {
return -1;
}
return q.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q.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();
*/