-
Notifications
You must be signed in to change notification settings - Fork 0
/
arrayQueue.java
108 lines (95 loc) · 2.82 KB
/
arrayQueue.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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import java.util.Objects;
import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
interface IQueue {
/*** Inserts an item at the queue front. */
public void enqueue(Object item);
/*** Removes the object at the queue rear and returnsit. */
public Object dequeue();
/*** Tests if this queue is empty. */
public boolean isEmpty();
/*** Returns the number of elements in the queue */
public int size();
}
public class ArrayQueue implements IQueue {
public static int N = 100;
public Object[] arr = new Object[N];
public int r = N - 1, f = N - 1;
public void enqueue(Object item) {
arr[r] = item;
if (r == 0) {
r = N - 1;
} else {
r--;
}
}
public Object dequeue() {
Object front = arr[f];
if (f == 0) {
f = N - 1;
} else {
f--;
}
return front;
}
public boolean isEmpty() {
return r == f;
}
public int size() {
return (N - r + f) % N;
}
public void printQ() {
if (r == f) {
System.out.println("[]");
} else {
System.out.print("[" + arr[r + 1]);
for (int i = r + 2; (N - r + f) % N != 1 && i != (f + 1) % N; i = (i + 1) % N) {
System.out.print(", " + arr[i]);
}
System.out.println("]");
}
}
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue();
Scanner sc = new Scanner(System.in);
String st = sc.nextLine().replaceAll("\\[|\\]", "");
String[] s = st.split(", ");
if (!(s.length == 1 && s[0].isEmpty())) {
for (int i = s.length - 1; i >= 0; i--) {
Object o = Integer.parseInt(s[i]);
queue.enqueue(o);
}
}
String keyword = sc.nextLine();
if (Objects.equals(keyword, "enqueue")) {
int element = sc.nextInt();
if (queue.size() < N - 1) {
queue.enqueue(element);
queue.printQ();
} else {
System.out.println("Error");
}
} else if (Objects.equals(keyword, "dequeue")) {
if (!queue.isEmpty()) {
queue.dequeue();
queue.printQ();
} else {
System.out.println("Error");
}
} else if (Objects.equals(keyword, "isEmpty")) {
if (queue.isEmpty()) {
System.out.println("True");
} else {
System.out.println("False");
}
} else if (Objects.equals(keyword, "size")) {
System.out.println(queue.size());
} else {
System.out.println("Error");
}
}
}