-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathQueueFromStack.java
57 lines (44 loc) · 1.21 KB
/
QueueFromStack.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
// you are given two stacks and using that make a queue
package queue.basic;
import java.util.Stack;
public class QueueFromStack {
static Stack<Integer> stack1 = new Stack<>();
static Stack<Integer> stack2 = new Stack<>();
public boolean isEmpty() {
return stack1.isEmpty();
}
public void enqueue(int element) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
stack1.push(element);
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
}
public int dequeue() {
if (stack1.isEmpty()) {
System.out.println("Empty Queue");
return -1;
}
return stack1.pop();
}
public int poll() {
if (stack1.isEmpty()) {
System.out.println("Empty Queue");
return -1;
}
return stack1.peek();
}
public static void main(String[] args) {
QueueFromStack queue = new QueueFromStack();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
while (!queue.isEmpty()) {
System.out.print(queue.poll() + " ");
queue.dequeue();
}
}
}