-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.java
75 lines (66 loc) · 1.34 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
import java.util.NoSuchElementException;
/**
* Queue implementation
*
* @author Kenneth
*
* @param <T> generic type of an item
*/
public class Queue<T> {
private Node first;
private Node last;
private int size;
private class Node {
private T item;
private Node next;
}
public Queue() {
this.first = null;
this.last = null;
this.size = 0;
}
/**
* Returns the node at the front of the line/queue
*
* @return the node at the front of the queue
*/
public T peek() {
if (this.size == 0) {
throw new NoSuchElementException("No elements in the queue");
} else {
return first.item;
}
}
/**
* Adds to the front of the line/queue
*
* @param item
*/
public void enqueue(T item) {
// Make the node to be added to the queue
Node oldLast = last;
last = new Node();
last.item = item;
last.next = null;
// Add the node to the queue
if (this.size == 0) {
this.first = this.last;
} else {
oldLast.next = last;
}
this.size++;
}
/**
* Removes from the front of the line/queue
*
* @param item
*/
public void dequeue() {
if (this.size == 0) {
throw new NoSuchElementException("No elements in the queue");
} else {
this.first = this.first.next;
this.size--;
}
}
}