-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueue.java
67 lines (58 loc) · 1.5 KB
/
Queue.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
public class Queue {
private int[] element;
private int front, rear, size, counter = 0;
//counter counts total number of elements
//size stores the maximum size of the queue
public Queue() {
element = new int[10];
size = 10;
front = 0;
rear = -1;
}
//overriding constructor with size
public Queue(int size) {
element = new int[size];
this.size = size;
front = 0;
rear = -1;
}
public void enqueue(int data) {
if (isFull())
System.out.println("Can't enqueue, Queue is full.");
else {
rear = (rear + 1) % size; //making the queue circular
element[rear] = data;
counter++;
}
}
public void dequeue() {
if (isEmpty())
System.out.println("The Queue is empty.");
else {
front = (front + 1) % size; //making the front pointer circular
counter--;
}
}
public int peek() {
if (isEmpty()) {
System.out.println("The Queue is empty.");
return -1;
}
return element[front];
}
public boolean isEmpty() {
return counter == 0;
}
public boolean isFull() {
return counter == size;
}
public int getSize() {
return counter;
}
public void print() {
for(int i = front; i != rear; i= (i+1)%size) {
System.out.print(element[i] + " ");
}
System.out.println();
}
}