225. Implement Stack using Queues
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.top(); // returns 2
stack.pop(); // returns 2
stack.empty(); // returns falseclass MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
queue<int> tmp;
while (!q.empty()) {
tmp.push(q.front());
q.pop();
}
q.push(x);
while (!tmp.empty()) {
q.push(tmp.front());
tmp.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int val = q.front(); q.pop();
return val;
}
/** Get the top element. */
int top() {
return q.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
private:
queue<int> q;
};Last updated