-
Notifications
You must be signed in to change notification settings - Fork 208
/
Copy pathQuestion3_7.java
executable file
·61 lines (58 loc) · 1.32 KB
/
Question3_7.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
57
58
59
60
61
package ca.mcmaster.offer;
import java.util.LinkedList;
public class Question3_7 {
private int order = 0;
private LinkedList<CatWrapper> cats = new LinkedList<>();
private LinkedList<DogWrapper> dogs = new LinkedList<>();
private class DogWrapper{
private int order;
private Animal dog;
public DogWrapper(int order, Animal dog) {
this.order = order;
this.dog = dog;
}
}
private class CatWrapper{
private int order;
private Animal cat;
public CatWrapper(int order, Animal cat) {
this.order = order;
this.cat = cat;
}
}
public void enqueue(Animal animal){
if(animal instanceof Cat){
cats.add(new CatWrapper(order, animal));
}else
dogs.add(new DogWrapper(order, animal));
order++;
}
public Dog dequeueDog(){
return (Dog)dogs.poll().dog;
}
public Cat dequeueCat(){
return (Cat)cats.poll().cat;
}
public Animal dequeueAny(){
DogWrapper dog = dogs.getFirst();
CatWrapper cat = cats.getFirst();
if(dog.order < cat.order)
return dequeueDog();
else
return dequeueCat();
}
public static void main(String[] args) {
Question3_7 queue = new Question3_7();
queue.enqueue(new Cat());
queue.enqueue(new Cat());
queue.enqueue(new Cat());
queue.enqueue(new Dog());
System.out.println(queue.dequeueDog());
}
}
class Dog extends Animal{
}
class Cat extends Animal{
}
class Animal{
}