-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.java
More file actions
62 lines (54 loc) · 1.64 KB
/
Queue.java
File metadata and controls
62 lines (54 loc) · 1.64 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
abstract class Animal {
private int order;
protected String name;
public Animal (String n) { name = n;}
public void setOrder(int ord) { order = ord; }
public int getOrder() { return order; }
/* Compare orders of animals to return the older item. */
public boolean isOlderThan(Animal a) {
return this.order <a.getOrder();
}
}
class AnimalQueue {
LinkedList<Dog> dogs = new LinkedList<Dog>();
LinkedList<Cat> cats = new LinkedList<Cat>();
private int order = 0; // acts as timestamp
public static void main(String[] args){
}
public void enqueue(Animal a) {
/* Order is used as a sort of timestamp, so that we can compare the insertion
* order of a dog to a cat.
*/
a.setOrder(order);
order++;
if(a instanceof Dog) dogs.addLast((Dog) a);
else if (a instanceof Cat) cats.addLast((Cat) a);
}
public Animal dequeueAny(){
/*Look at tops of a dog and cat queues, and pop the queue with the oldest value. */
if (dogs.size() == 0){
return dequeueCats();
} else if (cats.size() == 0) {
return dequeueDogs();
}
Dog dog = dogs.peek();
Cat cat = cats.peek();
if (dog.isOlderThan(cat)){
return dequeueDogs();
} else {
return dequeueCats();
}
}
public Dog dequeueDogs(){
return dogs.poll();
}
public Cat dequeueCats(){
return cats.poll();
}
}
public class Dog extends Animal {
public Dog (String n) { super(n); }
}
public class Cat extends Animal {
public Cat(String n){ super(n);}
}