-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedQueue.java
executable file
·97 lines (78 loc) · 2.01 KB
/
LinkedQueue.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
package com.example.queue;
import com.example.exceptions.EmptyCollectionException;
import com.example.interfaces.QueueADT;
import com.example.stack.LinearNode;
public class LinkedQueue<T> implements QueueADT<T> {
private int count;
private LinearNode<T> front, rear;
public LinkedQueue() {
this.count = 0;
this.front = null;
this.rear = null;
}
/**
* {@inheritDoc }
*/
@Override
public void enqueue(T element) {
LinearNode<T> newNode = new LinearNode<>(element);
if (isEmpty()) {
this.front = newNode;
this.rear = this.front;
} else {
this.rear.setNext(newNode);
this.rear = newNode;
}
this.count++;
}
/**
* {@inheritDoc }
*/
@Override
public T dequeue() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException(EmptyCollectionException.EMPTY_COLLECTION);
}
T removed = this.front.getElement();
this.front = this.front.getNext();
this.count--;
if (this.count == 0) {
this.rear = null;
}
return removed;
}
/**
* {@inheritDoc }
*/
@Override
public T first() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException(EmptyCollectionException.EMPTY_COLLECTION);
}
return this.front.getElement();
}
/**
* {@inheritDoc }
*/
@Override
public boolean isEmpty() {
return this.count == 0;
}
/**
* {@inheritDoc }
*/
@Override
public int size() {
return this.count;
}
protected String print() {
StringBuilder s = new StringBuilder();
LinearNode<T> current = this.front;
while (current != null) {
s.append(current.getElement()).append(" ");
current = current.getNext();
}
s.append("\n");
return s.toString();
}
}