232. Implement Queue using Stacks#

Approach/Intuition

LIFO + LIFO = FIFO

 1class MyQueue {
 2  Stack<Integer> s1, s2;
 3
 4  public MyQueue() {
 5    s1 = new Stack<>();
 6    s2 = new Stack<>();
 7  }
 8
 9  public void push(int x) {
10    s1.push(x);
11  }
12
13  public int pop() {
14    peek();
15    return s2.pop();
16  }
17
18  public int peek() {
19    if (s2.isEmpty()) {
20      while (!s1.isEmpty()) {
21        s2.push(s1.pop());
22      }
23    }
24    return s2.peek();
25  }
26
27  public boolean empty() {
28    return s1.isEmpty() && s2.isEmpty();
29  }
30}