-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueue.java
56 lines (45 loc) · 1.26 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
// Implemented with a singly-linked-list. I may add a
// separate implementation with ArrayLists or Vectors.
// Uses null value as an end-signifier.
import java.util.Iterator;
public class Queue<T> {
private Node head = null;
private Node tail = null;
private class Node {
T data;
Node next;
}
public void enqueue(T item) {
Node temp = tail;
tail = new Node();
tail.data = item;
if (isEmpty()) { head = tail; }
else { temp.next = temp; }
}
public T dequeue() {
if (head == null) { return null; }
T item = head.data;
head = head.next;
if (isEmpty()) { tail = null; }
return item;
}
public boolean isEmpty() {
return head == null;
}
public Iterator<T> iterator() {
return new QueueIterator();
}
private class QueueIterator implements Iterator<T> {
private Node current = head;
public boolean hasNext() {
return current != null;
}
public void remove() {/* unsupported, does nothing */}
public T next() {
if (current == null) { return null; }
T item = current.data;
current = current.next;
return item;
}
}
}