forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedQueue.java
More file actions
90 lines (78 loc) · 1.89 KB
/
LinkedQueue.java
File metadata and controls
90 lines (78 loc) · 1.89 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
83
84
85
86
87
88
89
90
package com.examplehub.datastructures.queue;
import com.examplehub.datastructures.linkedlist.Node;
import java.util.StringJoiner;
public class LinkedQueue<E> {
/** The front pointer of LinkedQueue. */
private Node<E> front;
/** The rear pointer of LinkedQueue. */
private Node<E> rear;
/** The number of elements in LinkedQueue. */
private int size;
public LinkedQueue() {
front = rear = null;
}
/**
* Remove item from the front of LinkedQueue.
*
* @return the item at the front of LinkedQueue.
* @throws IllegalAccessError if LinkedQueue is empty.
*/
public E dequeue() throws IllegalAccessException {
if (size == 0) {
throw new IllegalAccessException();
}
E retValue = front.data;
if ((front = front.next) == null) {
rear = null;
}
size--;
return retValue;
}
/**
* Added item to the rear of LinkedQueue.
*
* @param item the item to be added.
* @return {@code true} if add successfully.
*/
public boolean enqueue(E item) {
Node<E> newNode = new Node<>(item);
if (size == 0) {
front = rear = newNode;
} else {
rear = rear.next = newNode;
}
size++;
return true;
}
/**
* Test if this queue is empty or not.
*
* @return {@code true} if this queue is empty, otherwise {@code false}.
*/
public boolean empty() {
return size == 0;
}
@Override
public String toString() {
StringJoiner joiner = new StringJoiner(" <- ");
Node<E> temp = front;
while (temp != null) {
joiner.add(temp.data.toString());
temp = temp.next;
}
return joiner.toString();
}
/**
* Return the number of elements in this LinkedQueue.
*
* @return the number of elements in this LinkedQueue.
*/
public int size() {
return size;
}
/** Clear all elements in the LinkedQueue. */
public void clear() {
front = rear = null;
size = 0;
}
}