Loading

LeetCode problem#232

Implement Queue using Stacks

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

52 lines
1import java.util.Stack;
2
3class MyQueue {
4  private Stack<Integer> stack1;
5  private Stack<Integer> stack2;
6
7  public MyQueue() {
8      stack1 = new Stack<Integer>();
9      stack2 = new Stack<Integer>();
10  }
11  
12  public void push(int x) {
13      stack1.push(x);
14  }
15  
16  public int pop() {
17      if (stack2.empty()) {
18        while (!stack1.empty()) {
19          Integer popped = stack1.pop();
20          stack2.push(popped);
21        }
22      }
23
24      // assumption: stack2 is not empty, call to pop() valid and not trying to
25      // bring up exception for not having anything in queue
26      return stack2.pop();
27  }
28
29  public int peek() {
30    if (stack2.empty()) {
31      while (!stack1.empty()) {
32        Integer popped = stack1.pop();
33        stack2.push(popped);
34      }
35    }
36
37    return stack2.peek();
38  }
39  
40  public boolean empty() {
41      return stack1.empty() && stack2.empty();
42  }
43}
44
45/**
46* Your MyQueue object will be instantiated and called as such:
47* MyQueue obj = new MyQueue();
48* obj.push(x);
49* int param_2 = obj.pop();
50* int param_3 = obj.peek();
51* boolean param_4 = obj.empty();
52*/

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.