-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathArrayBasedQueue.java
104 lines (92 loc) · 1.77 KB
/
ArrayBasedQueue.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
/**
* Data-Structures-In-Java
* ArrayBasedQueue.java
*/
package com.deepak.data.structures.Queue;
import java.util.NoSuchElementException;
/**
* Implementation of array based queue
*
* @author Deepak
*/
public class ArrayBasedQueue {
/**
* Array of objects
*/
private Object[] array;
/**
* Size of queue
*/
int size = 0;
/**
* Since it is a queue, we need track of both head and tail
* Initial values to be 0
*/
int head = 0;
int tail = 0;
/**
* Constructor to create new array based queue
*
* @param capacity
*/
public ArrayBasedQueue(int capacity) {
array = new Object[capacity];
}
/**
* Method to push a new item in queue
* We will deal only with tail while adding new item
*
* @param item
*/
public void enqueue(Object item) {
if (size == array.length) {
throw new IllegalStateException("Cannot add to full queue");
}
array[tail] = item;
tail = (tail + 1) % array.length;
size++;
}
/**
* Method to pop a item from queue
* We will deal only with head while deleting a element
*
* @return {@link Object}
*/
public Object dequeue() {
if (size == 0) {
throw new NoSuchElementException("Cannot remove from empty queue");
}
Object item = array[head];
array[head] = null;
head = (head + 1) % array.length;
size--;
return item;
}
/**
* Method to check the top item in queue
*
* @return {@link Object}
*/
public Object peek() {
if (size == 0) {
throw new NoSuchElementException("Cannot peek from empty queue");
}
return array[head];
}
/**
* Method to check size of queue
*
* @return {@link int}
*/
public int size() {
return size;
}
/**
* Method to check if queue is empty
*
* @return {@link boolean}
*/
public boolean isEmpty() {
return size == 0;
}
}