-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedQueue.java
74 lines (63 loc) · 1.35 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
package br.unisinos.queue;
public class LinkedQueue<E> implements Queue<E> {
protected Node<E> first, last;
protected int numElements;
public LinkedQueue() {
first = last = null;
numElements = 0;
}
public boolean isEmpty() {
return numElements == 0;
}
public boolean isFull() {
// uma fila com alocação dinâmica nunca estará cheia!
return false;
}
public int numElements() {
return numElements;
}
public void enqueue(E element) {
Node<E> newNode = new Node<E>(element);
if (isEmpty())
first = last = newNode;
else {
last.setNext(newNode);
last = newNode;
}
numElements++;
}
public E dequeue() throws UnderflowException {
if (isEmpty())
throw new UnderflowException();
E element = first.getElement();
if (first == last)
first = last = null;
else
first = first.getNext();
numElements--;
return element;
}
public E front() throws UnderflowException {
if (isEmpty())
throw new UnderflowException();
return first.getElement();
}
public E back() {
if (isEmpty())
throw new UnderflowException();
return last.getElement();
}
public String toString() {
if (isEmpty())
return "[Empty]";
else {
String s = "[" + first.getElement();
Node<E> cur = first.getNext();
while (cur != null) {
s += ", " + cur.getElement();
cur = cur.getNext();
}
return s + "]";
}
}
}