forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyQueue.java
More file actions
48 lines (38 loc) · 1.11 KB
/
MyQueue.java
File metadata and controls
48 lines (38 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Time Complexity : O(1)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Approach:
// Use one stack for push operations and another for pop/peek.
// Transfer elements only when needed to maintain FIFO order.
import java.util.Stack;
class MyQueue {
Stack<Integer> inputStack;
Stack<Integer> outputStack;
public MyQueue() {
this.inputStack = new Stack<>();
this.outputStack = new Stack<>();
}
public void push(int x) {
inputStack.push(x);
}
public int pop() {
if (outputStack.isEmpty()) {
while (!inputStack.isEmpty()) {
outputStack.push(inputStack.pop());
}
}
return outputStack.pop();
}
public int peek() {
if (outputStack.isEmpty()) {
while (!inputStack.isEmpty()) {
outputStack.push(inputStack.pop());
}
}
return outputStack.peek();
}
public boolean empty() {
return inputStack.isEmpty() && outputStack.isEmpty();
}
}