/**
* 225. Implement Stack using Queues
* 1. Time:O() Space:O()
* 2. Time:O() Space:O()
* 3. Time:O() Space:O()
*/
// 1. Time:O() Space:O()
class MyStack {
private Queue<Integer> q1 = new LinkedList<>();
private Queue<Integer> q2 = new LinkedList<>();
private int top;
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
q1.add(x);
top = x;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
while(q1.size()>1){
top = q1.remove();
q2.add(top);
}
int a = q1.remove();
Queue<Integer> tmp = q1;
q1 = q2;
q2 = tmp;
return a;
}
/** Get the top element. */
public int top() {
return top;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}
// 2. Time:O() Space:O()
class MyStack {
private Queue<Integer> q1 = new LinkedList<>();
private Queue<Integer> q2 = new LinkedList<>();
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
q2.add(x);
while(q1.size()>0){
q2.add(q1.remove());
}
Queue<Integer> tmp = q1;
q1 = q2;
q2 = tmp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q1.remove();
}
/** Get the top element. */
public int top() {
return q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}
// 3. Time:O() Space:O()
class MyStack {
private Queue<Integer> q = new LinkedList<>();
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
q.add(x);
int size = q.size();
while(size>1){
q.add(q.remove());
size--;
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q.remove();
}
/** Get the top element. */
public int top() {
return q.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q.isEmpty();
}
}