-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.java
More file actions
104 lines (81 loc) · 2.3 KB
/
Queue.java
File metadata and controls
104 lines (81 loc) · 2.3 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Queue<Vertex> implements Iterable<Vertex> {
private int n; // number of elements on queue
private Node first; // beginning of queue
private Node last; // end of queue
private class Node {
private Vertex item;
private Node next;
}
public Queue() {
first = null;
last = null;
n = 0;
}
public boolean isEmpty() {
return first == null;
}
/**
* Returns the number of items in this queue.
*
* @return the number of items in this queue
*/
public int size() {
return n;
}
/**
* Returns the number of items in this queue.
*
* @return the number of items in this queue
*/
public int length() {
return n;
}
public int peek() {
if (isEmpty()) throw new NoSuchElementException();
return (int) first.item;
}
/**
* Add the item to the queue.
*/
public void enqueue(Vertex item) {
Node oldlast = last;
last = new Node();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
n++;
}
public Vertex dequeue() {
if (isEmpty()) throw new NoSuchElementException();
Vertex item = first.item;
first = first.next;
n--;
if (isEmpty()) last = null; // to avoid loitering
return item;
}
public String toString() {
StringBuilder s = new StringBuilder();
for (Vertex item : this) {
s.append(item);
s.append(' ');
}
return s.toString();
}
public Iterator<Vertex> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Vertex> {
private Node current = first;
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
public Vertex next() {
if (!hasNext()) throw new NoSuchElementException();
Vertex item = current.item;
current = current.next;
return item;
}
}
}