-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.java
More file actions
56 lines (48 loc) · 1.41 KB
/
Queue.java
File metadata and controls
56 lines (48 loc) · 1.41 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
public class Queue<T> implements Iterator<T> {
private Node first;
private Node second;
private class Node {
private T item;
private Node next;
}
public boolean isEmpty() {
return first == null;
}
public void enqueue(T item) {
Node oldSecond = second;
second = new Node();
second.item = item;
second.next = null;
if (isEmpty()) first = second;
else oldSecond.next = second;
}
public T dequeue() {
T item = first.item;
first = first.next;
if (isEmpty()) second = null;
return item;
}
public static void main(String[] args) {
Queue<Integer> ints = new Queue<>();
ints.enqueue(1);
ints.enqueue(2);
ints.enqueue(3);
while(!ints.isEmpty()) {
System.out.println(ints.dequeue());
}
Queue<String> strings = new Queue<>();
strings.enqueue("1");
strings.enqueue("hello");
strings.enqueue("world");
while(!strings.isEmpty()) {
System.out.println(strings.dequeue());
}
Queue<Animal> animals = new Queue<>();
animals.enqueue(new Cat("Brown", "Roadhouse"));
animals.enqueue(new Cat("Black", "Bub"));
animals.enqueue(new Cat("Gray", "Pickles"));
while(!animals.isEmpty()) {
System.out.println(animals.dequeue());
}
}
}