-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathstack_using_queue.java
79 lines (60 loc) · 1.99 KB
/
stack_using_queue.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
73
74
75
76
77
78
79
// stack using queues
import java.util.LinkedList;
import java.util.Queue;
public class StackUsingQueues {
private Queue<Integer> primaryQueue;
private Queue<Integer> tempQueue;
public StackUsingQueues() {
primaryQueue = new LinkedList<>();
tempQueue = new LinkedList<>();
}
public void push(int value) {
// Add the element to the primary queue
primaryQueue.offer(value);
}
public int pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty.");
}
// Move elements from the primary queue to the temporary queue except the last one
while (primaryQueue.size() > 1) {
tempQueue.offer(primaryQueue.poll());
}
// Get the last element from the primary queue (top of the stack)
int topElement = primaryQueue.poll();
// Swap the primary and temporary queues
Queue<Integer> swap = primaryQueue;
primaryQueue = tempQueue;
tempQueue = swap;
return topElement;
}
public int top() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty.");
}
int topElement = pop();
// Add the top element back to the stack
push(topElement);
return topElement;
}
public boolean isEmpty() {
return primaryQueue.isEmpty();
}
public static void main(String[] args) {
StackUsingQueues stack = new StackUsingQueues();
// Push elements onto the stack
stack.push(1);
stack.push(2);
stack.push(3);
// Pop elements from the stack
System.out.println(stack.pop()); // Output: 3
System.out.println(stack.pop()); // Output: 2
// Push more elements
stack.push(4);
stack.push(5);
// Peek at the top element
System.out.println(stack.top()); // Output: 5
// Check if the stack is empty
System.out.println(stack.isEmpty()); // Output: false
}
}