猫狗队列
程序员文章站
2022-07-14 12:14:52
...
【题目】
宠物、狗和猫的类如下:
package algorithm_and_data_structure.stack_and_queue;
public class Pet {
private String type;
public Pet(String type) {
this.type = type;
}
public String getType() {
return type;
}
}
class Cat extends Pet {
public Cat() {
super("cat");
}
}
class Dog extends Pet {
public Dog() {
super("dog");
}
}
实现一种猫狗队列的结构,要求如下:
- 用户可以调用add方法将cat类或dog类的实例放入队列中;
- 用户可以调用pollAll方法,将队列中所有的实例按照进队列的先后顺序依次弹出;
- 用户可以调用pollCat方法,将队列中cat类的实例按照进队列的先后顺序依次弹出;
- 用户可以调用pollDog方法,将队列中dog类的实例按照进队列的先后顺序依次弹出;
- 用户可以调用isEmpty方法,检查队列中是否还有dog类或cat类的实例;
- 用户可以调用isCatEmpty方法,检查队列中是否还有cat类的实例;
- 用户可以调用isDogEmpty方法,检查队列中是否还有dog类的实例。
package algorithm_and_data_structure.stack_and_queue;
import java.util.LinkedList;
import java.util.Queue;
public class CatDogQueue {
private Queue<PetEnterQueue> catEnterQueue;
private Queue<PetEnterQueue> dogEnterQueue;
private int counter;
public CatDogQueue() {
catEnterQueue = new LinkedList<PetEnterQueue>();
dogEnterQueue = new LinkedList<PetEnterQueue>();
counter = 0;
}
public void add(Pet pet) {
if (pet instanceof Cat) {
catEnterQueue.add(new PetEnterQueue(pet, counter++));
} else if (pet instanceof Dog) {
dogEnterQueue.add(new PetEnterQueue(pet, counter++));
} else {
throw new RuntimeException("error, not cat or dog!");
}
}
public Pet pollAll() {
if (!catEnterQueue.isEmpty() && !dogEnterQueue.isEmpty()) {
return catEnterQueue.peek().getCounter() < dogEnterQueue.peek().getCounter() ? catEnterQueue.poll().getPet() : dogEnterQueue.poll().getPet();
} else if (!catEnterQueue.isEmpty()) {
return catEnterQueue.poll().getPet();
} else if (!dogEnterQueue.isEmpty()) {
return dogEnterQueue.poll().getPet();
} else {
throw new RuntimeException("error, queue is empty!");
}
}
public Cat pollCat() {
if (!catEnterQueue.isEmpty()) {
return (Cat) catEnterQueue.poll().getPet();
} else {
throw new RuntimeException("error, cat queue is empty!");
}
}
public Dog pollDog() {
if (!dogEnterQueue.isEmpty()) {
return (Dog) dogEnterQueue.poll().getPet();
} else {
throw new RuntimeException("error, dog queue is empty!");
}
}
public boolean isEmpty() {
return catEnterQueue.isEmpty() && dogEnterQueue.isEmpty();
}
public boolean isCatEmpty() {
return catEnterQueue.isEmpty();
}
public boolean isDogEmpty() {
return dogEnterQueue.isEmpty();
}
}
class PetEnterQueue {
private Pet pet;
private int counter;
public PetEnterQueue(Pet pet, int counter) {
this.pet = pet;
this.counter = counter;
}
public Pet getPet() {
return pet;
}
public int getCounter() {
return counter;
}
public String getEnterPetType() {
return pet.getType();
}
}
转载于:https://www.jianshu.com/p/2c035673b982
上一篇: jsonp跨域到底是怎么一回事?
下一篇: 函数预编译是怎么一回事?