Skip to content

Instantly share code, notes, and snippets.

@jyhjuzi
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jyhjuzi/de9393fb070b4061d34e to your computer and use it in GitHub Desktop.
Save jyhjuzi/de9393fb070b4061d34e to your computer and use it in GitHub Desktop.
import java.util.LinkedList;
public class Q3_7{
public static void main(String[] args){
Dog[] dogs = {new Dog("doga"),new Dog("dogb"),new Dog("dogc"),new Dog("dogd"),new Dog("doge")};
Cat[] cats = {new Cat("cata"),new Cat("catb"),new Cat("catc")};
AnimalShelter ash = new AnimalShelter();
ash.enqueue(dogs[0]);
ash.enqueue(dogs[1]);
System.out.println(ash.dequeueDog().name);
ash.enqueue(cats[0]);
System.out.println(ash.dequeueAny().name);
System.out.println(ash.dequeueAny().name);
ash.enqueue(dogs[2]);
ash.enqueue(cats[1]);
ash.enqueue(cats[2]);
ash.enqueue(dogs[3]);
ash.enqueue(dogs[4]);
System.out.println(ash.size());
for(int i = 0; i< 5;i++){
System.out.println(ash.dequeueAny().name);
}
}
}
class AnimalShelter{
LinkedList<Dog> dogs;
LinkedList<Cat> cats;
int order;
AnimalShelter(){
dogs = new LinkedList<Dog>();
cats = new LinkedList<Cat>();
order = 1;
}
void enqueue(Animal animal){
if(animal.getClass()== Cat.class){
Cat c = (Cat)animal;
c.setOrder(order);
cats.add(c);
order++;
}
else if(animal.getClass()== Dog.class){
Dog d = (Dog)animal;
d.setOrder(order);
dogs.add(d);
order++;
}
}
Animal dequeueAny(){
if(dogs.isEmpty()&& cats.isEmpty())
return null;
if(!dogs.isEmpty()&& !cats.isEmpty()){
Dog d = dogs.getFirst();
Cat c = cats.getFirst();
return d.getOrder()<c.getOrder() ? dogs.removeFirst():cats.removeFirst();
}
else return dogs.isEmpty()? cats.removeFirst():dogs.removeFirst();
}
Dog dequeueDog(){
if(dogs.isEmpty())
return null;
else
return dogs.removeFirst();
}
Cat dequeueCat(){
if(cats.isEmpty())
return null;
else
return cats.removeFirst();
}
int size(){
return cats.size()+dogs.size();
}
}
abstract class Animal{
String name;
int order;
Animal(String n){
name = n;
}
void setOrder(int o){
this.order = o;
}
int getOrder(){
return order;
}
}
class Dog extends Animal{
Dog(String s){
super(s);
}
}
class Cat extends Animal{
Cat(String s){
super(s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment