-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.java
100 lines (86 loc) · 1.97 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
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
package dsa_dp.data_structures.queue;
import dsa_dp.data_structures.linked_list.SinglyLinkedList;
public class Queue<T> {
private final SinglyLinkedList<T> list = new SinglyLinkedList<>();
private int maxSize = -1;
/**
* Default constructor
*/
public Queue() {
}
/**
* Given max size constructor
*
* @param maxSize int
*/
public Queue(int maxSize) {
this.maxSize = maxSize;
}
/**
* Constructor with given max size and first entry
*/
public Queue(int maxSize, T item) {
this.enqueue(item);
this.maxSize = maxSize;
}
/**
* Adds a new item to the head of the list
*
* @param item T
*/
public void enqueue(T item) {
this.list.add(item);
}
/**
* Removes and returns the first element added to the queue
* (Front of the Queue)
*
* @return T
* @throws IndexOutOfBoundsException exception
*/
public T dequeue() throws IndexOutOfBoundsException {
T data = this.list.get(0);
this.list.remove(0);
return data;
}
/**
* Reads the element at the front of the queue without removing it
*
* @return T
*/
public T peek() {
return this.list.get(0);
}
/**
* Returns true if the Queue reached it's max size
* A queue with a -1 max size doesn't reach a 'full' state
*
* @return boolean
*/
public boolean isFull() {
return this.maxSize != -1 && this.list.size() >= this.maxSize;
}
/**
* Returns true if the Queue size is equal to 0
*
* @return boolean
*/
public boolean isEmpty() {
return this.list.size() <= 0;
}
/**
* Returns the current Queue size
*
* @return int
*/
public int size() {
return this.list.size();
}
/**
* Prints the Queue in a suitable format
* O(n)
*/
public void print() {
this.list.print();
}
}