Last active
August 29, 2015 14:03
-
-
Save jingz8804/65e1472abd08b3a14f82 to your computer and use it in GitHub Desktop.
#ctci
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Date; | |
public class Animal{ | |
String type; | |
Date arrived; | |
} | |
public class Dog extends Animal{ | |
String name; | |
public Dog(String name){ | |
super(); | |
this.name = name; | |
type = "Dog"; | |
} | |
} | |
public class Cat extends Animal{ | |
String name; | |
public Cat(String name){ | |
super(); | |
this.name = name; | |
type = "Cat"; | |
} | |
} | |
import java.util.Queue; | |
import java.util.LinkedList; | |
import java.util.Date; | |
public class AnimalShelter{ | |
private Queue<Cat> cats; | |
private Queue<Dog> dogs; | |
public AnimalShelter(){ | |
cats = new LinkedList<Cat>(); | |
dogs = new LinkedList<Dog>(); | |
} | |
public void enqueue(Animal animal) throws Exception{ | |
boolean isCat = animal.type.equals("Cat"); | |
boolean isDog = animal.type.equals("Dog"); | |
if(!isCat && !isDog) | |
throw new Exception("Unknow type of animal!"); | |
animal.arrived = new Date(); | |
if(isCat) cats.offer((Cat) animal); | |
else dogs.offer((Dog) animal); | |
} | |
public Animal dequeueAny() throws Exception{ | |
boolean noCat = cats.isEmpty(); | |
boolean noDog = dogs.isEmpty(); | |
if(noCat && noDog) throw new Exception("There are no more animals!"); | |
if(noDog) return cats.poll(); | |
if(noCat) return dogs.poll(); | |
return cats.peek().arrived.compareTo(dogs.peek().arrived) < 0 ? cats.poll() : dogs.poll(); | |
} | |
public Cat dequeueCat() throws Exception{ | |
boolean noCat = cats.isEmpty(); | |
if(noCat) throw new Exception("There are no more cats!"); | |
return cats.poll(); | |
} | |
public Dog dequeueDog() throws Exception{ | |
boolean noDog = dogs.isEmpty(); | |
if(noDog) throw new Exception("There are no more dogs!"); | |
return dogs.poll(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment