-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.java
More file actions
82 lines (71 loc) · 2.02 KB
/
Copy pathQueue.java
File metadata and controls
82 lines (71 loc) · 2.02 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
/*
The Generic Queue implementation uses ArrayList as the underlying data structure. It
follows FIFO (First In, First Out) where the tail of the queue is at the beginning
of the ArrayList and the head is at the end. This is to be used in the checkout
simulation to manage customer lines.
*/
import java.util.ArrayList;
import java.util.NoSuchElementException;
public class Queue<T> {
/*
* The tail of the queue is at the beginning
* of the ArrayList; the head is the last item
*/
ArrayList<T> items;
/*
* Create a new Queue
*/
public Queue() {
this.items = new ArrayList<T>();
}
/*
* Returns true if there are no items in the queue;
* false otherwise.
*/
public boolean isEmpty() {
return (this.items.isEmpty());
}
/*
* Add an item to the tail of the queue
*/
public void enqueue(T item) {
this.items.add(0, item);
}
/*
* Remove the item at the head of the queue and return it.
* If the queue is empty, throws an exception.
*/
public T dequeue() {
if (this.isEmpty()) {
throw new NoSuchElementException("Queue is empty.");
}
return this.items.remove(this.size() - 1);
}
/*
* Return the item at the head of the queue, but do not remove it.
* If the queue is empty, throws an exception.
*/
public T peek() {
if (this.isEmpty()) {
throw new NoSuchElementException("Queue is empty.");
}
return this.items.get(this.size() - 1);
}
/*
* Returns the number of items in the queue.
*/
public int size() {
return this.items.size();
}
/*
* Convert to string as an array from tail to head
*/
public String toString() {
if (!this.items.isEmpty()) {
String arrString = this.items.toString();
return "tail ->" + arrString + "-> head";
} else {
return "<<empty queue>>";
}
}
}