forked from dimpeshpanwar/Java-Advance-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingQueues.java
More file actions
46 lines (36 loc) · 981 Bytes
/
StackUsingQueues.java
File metadata and controls
46 lines (36 loc) · 981 Bytes
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
// Implementing a Stack Using Queues
// Create a stack using two queues.
import java.util.LinkedList;
import java.util.Queue;
public class StackUsingQueues {
private Queue<Integer> queue1;
private Queue<Integer> queue2;
public StackUsingQueues() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
public void push(int x) {
queue2.offer(x);
while (!queue1.isEmpty()) {
queue2.offer(queue1.poll());
}
Queue<Integer> tempQueue = queue1;
queue1 = queue2;
queue2 = tempQueue;
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.isEmpty();
}
public static void main(String[] args) {
StackUsingQueues stack = new StackUsingQueues();
stack.push(1);
stack.push(2);
System.out.println(stack.pop()); // Output: 2
}
}