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 false解题要点:
Last updated
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.top(); // returns 2
stack.pop(); // returns 2
stack.empty(); // returns falseLast updated
class MyStack {
Queue<Integer> q1;
Queue<Integer> q2;
int size;
/** Initialize your data structure here. */
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
size = 0;
}
/** Push element x onto stack. */
public void push(int x) {
q2.add(x);
while(q1.size() > 0){
q2.add(q1.poll());
}
while(q2.size() > 0){
q1.add(q2.poll());
}
size++;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
size--;
return q1.poll();
}
/** Get the top element. */
public int top() {
return q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return size == 0;
}
}
/**
* 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();
* boolean param_4 = obj.empty();
*/