-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwo Queue Stack
72 lines (59 loc) · 2.01 KB
/
Two Queue Stack
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
package DataS;
import java.util.LinkedList;
import java.util.Queue;
public class Two_Queue_Stack_Implementation {
static class TwoQueueStack {
private Queue<Integer> queue1;
private Queue<Integer> queue2;
public TwoQueueStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
public void push(int x) {
queue1.add(x);
}
public int pop() {
if (queue1.isEmpty()) {
throw new RuntimeException("Stack is empty");
}
while (queue1.size() > 1) {
queue2.add(queue1.remove());
}
int poppedElement = queue1.remove();
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;
return poppedElement;
}
public int top() {
if (queue1.isEmpty()) {
throw new RuntimeException("Stack is empty");
}
while (queue1.size() > 1) {
queue2.add(queue1.remove());
}
int topElement = queue1.peek();
queue2.add(queue1.remove());
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;
return topElement;
}
public boolean isEmpty() {
return queue1.isEmpty();
}
}
public static void main(String[] args) {
TwoQueueStack stack = new TwoQueueStack();
stack.push(5);
stack.push(12);
stack.push(20);
System.out.println("Top element: " + stack.top());
System.out.println("Popped element: " + stack.pop());
System.out.println("Top element after pop: " + stack.top());
System.out.println("Is stack empty? " + stack.isEmpty());
stack.pop();
stack.pop();
System.out.println("Is stack empty after popping all elements? " + stack.isEmpty());
}
}