-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack using Two Queues in Java
More file actions
81 lines (62 loc) · 2.18 KB
/
Stack using Two Queues in Java
File metadata and controls
81 lines (62 loc) · 2.18 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
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
80
81
import java.util.LinkedList;
import java.util.Queue;
public class TwoQueueStack<T> {
private Queue<T> queue1;
private Queue<T> queue2;
public TwoQueueStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
public void push(T element) {
// Add the element to queue1
queue1.add(element);
}
public T pop() {
if (queue1.isEmpty())
throw new IllegalStateException("Stack is empty");
// Move all elements except the last one from queue 1 to queue 2
while (queue1.size() > 1) {
queue2.add(queue1.remove());
}
// Retrieve the last element from queue 1, which is the top of the stack
T poppedElement = queue1.remove();
// Swap the references of queue 1 and queue 2
Queue<T> temp = queue1;
queue1 = queue2;
queue2 = temp;
return poppedElement;
}
public T peek() {
if (queue1.isEmpty())
throw new IllegalStateException("Stack is empty");
T topElement = null;
// Move all elements except the last one from queue 1 to queue 2
while (!queue1.isEmpty()) {
topElement = queue1.remove();
queue2.add(topElement);
}
// Swap the references of queue 1 and queue 2
Queue<T> temp = queue1;
queue1 = queue2;
queue2 = temp;
return topElement;
}
public boolean isEmpty() {
return queue1.isEmpty();
}
public int size() {
return queue1.size();
}
public static void main(String[] args) {
TwoQueueStack<Integer> stack = new TwoQueueStack<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Size of stack: " + stack.size());
System.out.println("Top element of stack: " + stack.peek());
System.out.println("Pop: " + stack.pop());
System.out.println("Pop: " + stack.pop());
System.out.println("Pop: " + stack.pop());
System.out.println("Is stack empty? " + stack.isEmpty());
}
}