forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyQueue.java
72 lines (56 loc) · 1.95 KB
/
MyQueue.java
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Time Complexity : Ammortized O(1)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : no
import java.util.Stack;
public class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
//Constructor
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
// Push element into stack1 which will be the back of the Queue
public void push(int x){
stack1.push(x);
}
public int pop() {
peek();
// return the top of stack 2
return stack2.pop();
}
public int peek() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
public boolean empty(){
return stack1.isEmpty() && stack2.isEmpty();
}
// Main method to test the implementation
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
// Push elements to the queue
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
// Peek the front element
System.out.println("Front element: " + myQueue.peek()); // Should print 1
// Pop elements from the queue
System.out.println("Popped element: " + myQueue.pop()); // Should print 1
System.out.println("Popped element: " + myQueue.pop()); // Should print 2
// Push another element
myQueue.push(4);
// Peek the front element
System.out.println("Front element: " + myQueue.peek()); // Should print 3
// Pop remaining elements
System.out.println("Popped element: " + myQueue.pop()); // Should print 3
System.out.println("Popped element: " + myQueue.pop()); // Should print 4
// Check if the queue is empty
System.out.println("Is queue empty? " + myQueue.empty()); // Should print true
}
}