-
Notifications
You must be signed in to change notification settings - Fork 28
/
Queue.java
75 lines (58 loc) · 1.51 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
package com.anthonynsimon.datastructures;
import com.anthonynsimon.datastructures.util.SinglyNode;
public class Queue<E> {
protected int size;
protected SinglyNode<E> head;
protected SinglyNode<E> tail;
public Queue() {
this.size = 0;
this.head = null;
this.tail = null;
}
public int size() {
return this.size;
}
public E peek() {
if (size() == 0) {
return null;
}
return this.head.getData();
}
// Append element to the tail (back) of the queue.
// Move tail pointer to this new element.
public void enqueue(E item) {
SinglyNode<E> newNode = new SinglyNode<>(item);
if (size() == 0) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.setNext(newNode);
this.tail = newNode;
}
this.size++;
}
// Pop and return element from the head (front) of the queue.
// Move head pointer to next element in line.
public E dequeue() {
if (size() == 0) {
return null;
}
E temp = this.head.getData();
if (size() == 1) {
this.head = null;
this.tail = null;
} else {
this.head = this.head.getNext();
}
this.size--;
return temp;
}
public void clear() {
this.size = 0;
this.head = null;
this.tail = null;
}
public boolean isEmpty() {
return size() == 0;
}
}