Queue 2개로 Stack구현하기
import java.util.LinkedList;
import java.util.Queue;
public class Stack<T> {
private Queue<T> q1;
private Queue<T> q2;
public Stack() {
this.q1 = new LinkedList<>();
this.q2 = new LinkedList<>();
}
public void push(T value) {
q1.add(value);
}
public T pop() {
while (q1.size() > 1) {
q2.add(q1.poll());
}
Queue<T> temp = q1;
q1 = q2;
q2 = temp;
return q2.poll();
}
@Override
public String toString() {
return "Stack{" +
"q1=" + q1 +
", q2=" + q2 +
'}';
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println(stack.pop());
System.out.println(stack);
System.out.println(stack.pop());
System.out.println(stack);
}
}