MCPcopy Create free account
hub / github.com/careercup/ctci / AnimalQueue

Class AnimalQueue

java/Chapter 3/Question3_7/AnimalQueue.java:5–69  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

3import java.util.LinkedList;
4
5public class AnimalQueue {
6 LinkedList<Dog> dogs = new LinkedList<Dog>();
7 LinkedList<Cat> cats = new LinkedList<Cat>();
8 private int order = 0;
9
10 public void enqueue(Animal a) {
11 a.setOrder(order);
12 order++;
13 if (a instanceof Dog) {
14 dogs.addLast((Dog) a);
15 } else if (a instanceof Cat) {
16 cats.addLast((Cat)a);
17 }
18 }
19
20 public Animal dequeueAny() {
21 if (dogs.size() == 0) {
22 return dequeueCats();
23 } else if (cats.size() == 0) {
24 return dequeueDogs();
25 }
26 Dog dog = dogs.peek();
27 Cat cat = cats.peek();
28 if (dog.isOlderThan(cat)) {
29 return dogs.poll();
30 } else {
31 return cats.poll();
32 }
33 }
34
35 public Animal peek() {
36 if (dogs.size() == 0) {
37 return cats.peek();
38 } else if (cats.size() == 0) {
39 return dogs.peek();
40 }
41 Dog dog = dogs.peek();
42 Cat cat = cats.peek();
43 if (dog.isOlderThan(cat)) {
44 return dog;
45 } else {
46 return cat;
47 }
48 }
49
50 public int size() {
51 return dogs.size() + cats.size();
52 }
53
54 public Dog dequeueDogs() {
55 return dogs.poll();
56 }
57
58 public Dog peekDogs() {
59 return dogs.peek();
60 }
61
62 public Cat dequeueCats() {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected