-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueUsingStack.java
More file actions
57 lines (45 loc) · 1.69 KB
/
Copy pathQueueUsingStack.java
File metadata and controls
57 lines (45 loc) · 1.69 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
package Queue;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.stream.IntStream;
class QueueUsingStack {
public static void main(String[] args) {
System.out.println("implementation of queue using insertionStack");
int size = 5;
QueueImplementation<Integer> queueImplementation = new QueueImplementation<>(size);
queueImplementation.enqueue(2);
System.out.println(queueImplementation.dequeue());
IntStream.range(0, size).forEach(queueImplementation::enqueue);
IntStream.range(0, size - 1).forEach(i -> {
System.out.print(queueImplementation.dequeue() + ", ");
});
System.out.println("\n"+ queueImplementation.dequeue());
}
}
class QueueImplementation<E> {
int CAPACITY;
Deque<E> insertionStack;
Deque<E> removalStack;
QueueImplementation(int size) {
this.CAPACITY = size;
this.insertionStack = new ArrayDeque<>();
this.removalStack = new ArrayDeque<>();
}
public void enqueue(E e) {
if (this.insertionStack.size() == this.CAPACITY) {
throw new RuntimeException("queue is full, remove at least one element before inserting.");
}
this.insertionStack.push(e);
}
public E dequeue() {
if (this.insertionStack.isEmpty() && this.removalStack.isEmpty()) {
throw new RuntimeException("queue is empty, insert an element before retrieving.");
}
if (this.removalStack.isEmpty()) {
while (!this.insertionStack.isEmpty()) {
this.removalStack.push(this.insertionStack.pop());
}
}
return removalStack.pop();
}
}