-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayImplementation.java
More file actions
84 lines (72 loc) · 2.05 KB
/
ArrayImplementation.java
File metadata and controls
84 lines (72 loc) · 2.05 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
82
83
84
package Queue;
import java.lang.reflect.Array;
import java.util.EmptyStackException;
/**
* Array Implementation of Queue.
* Disadvantages -> size issue.
*/
public class ArrayImplementation {
public static void main(String[] args) {
QueueArray<Integer> q = new QueueArray<>(Integer.class, 5);
q.add(2);
q.add(5);
q.add(8);
System.out.println(q.remove());
q.display();
}
public static class QueueArray<T> {
private final T[] arr;
int size = 0;
private int front = -1;
private int rear = -1;
@SuppressWarnings("unchecked")
public QueueArray(Class<T> clazz) {
arr = (T[]) Array.newInstance(clazz, 100);
}
@SuppressWarnings("unchecked")
public QueueArray(Class<T> clazz, int size) {
arr = (T[]) Array.newInstance(clazz, size);
}
// Add Function
public void add(T val) {
if (rear == arr.length - 1) {
System.out.println("Queue is Full!");
return;
}
if (front == -1) {
front = rear = 0;
arr[rear] = val;
} else {
arr[++rear] = val;
}
size++;
}
// Remove Function
public T remove() {
if (size == 0) {
throw new EmptyStackException();
}
front++;
size--;
return arr[front - 1];
}
// Return the First Element
public T peek() {
if (size == 0) {
throw new EmptyStackException();
}
return arr[front];
}
// Display the Queue from rear to front.
public void display() {
if (size == 0) {
System.out.println("Queue is Empty!");
} else {
for (int i = front; i <= rear; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
}
}