题目
实现猫狗队列
代码实现
//宠物类
class Pet {
private String type;
public Pet(String type) {
this.type = type;
}
public String getPetType() {
return this.type;
}
}
//狗类
class Dog extends Pet {
public Dog() {
super("dog");
}
}
//猫类
class Cat extends Pet {
public Cat() {
super("cat");
}
}
//添加了时间戳的宠物类
class PetEnterQueue {
private Pet pet;
private long count;
public PetEnterQueue(Pet pet, long count) {
this.pet = pet;
this.count = count;
}
public Pet getPet() {
return this.pet;
}
public long getCount() {
return this.count;
}
}
//猫狗类
public class DogCatQueue {
private Queue<PetEnterQueue> dogQ;
private Queue<PetEnterQueue> catQ;
private long count;
public DogCatQueue() {
this.dogQ = new LinkedList<PetEnterQueue>();
this.catQ = new LinkedList<PetEnterQueue>();
this.count = 0;
}
//将cat类或dog类的实例放入队列中
public void add(Pet pet) {
if (pet.getPetType().equals("dog")) {
this.dogQ.add(new PetEnterQueue(pet, this.count++));
} else if (pet.getPetType().equals("cat")) {
this.catQ.add(new PetEnterQueue(pet, this.count++));
} else {
throw new RuntimeException("err, not dog or cat");
}
}
//将队列中所有的实例按照进队列的先后顺序依次弹出
public Pet pollAll() {
if (!isDogQueueEmpty() && !isCatQueueEmpty()) {
if (this.dogQ.peek().getCount() < this.catQ.peek().getCount()) {
return this.dogQ.poll().getPet();
} else {
return this.catQ.poll().getPet();
}
} else if (!this.isDogQueueEmpty()) {
return this.dogQ.poll().getPet();
} else if (!this.isCatQueueEmpty()) {
return this.catQ.poll().getPet();
} else {
throw new RuntimeException("err, queue is empty!");
}
}
//将队列中dog类的实例按照进队列的先后顺序依次弹出
public Dog pollDog() {
if (!this.isDogQueueEmpty()) {
return (Dog) this.dogQ.poll().getPet();
} else {
throw new RuntimeException("Dog queue is empty!");
}
}
//将队列中cat类的实例按照进队列的先后顺序依次弹出
public Cat pollCat() {
if (!this.isCatQueueEmpty()) {
return (Cat) this.catQ.poll().getPet();
} else {
throw new RuntimeException("Cat queue is empty!");
}
}
//检查队列中是否还有dog或者cat的实例
public boolean isEmpty() {
return isDogQueueEmpty() && isCatQueueEmpty();
}
//检查队列中是否有dog类的实例
public boolean isDogQueueEmpty() {
return this.dogQ.isEmpty();
}
//检查队列中是否有cat类的实例
public boolean isCatQueueEmpty() {
return this.catQ.isEmpty();
}
}