要求:已知有如下的数据结构,实现一种猫狗队列,具有:
add:将cat dog 插入队列
pollAll:将所有猫狗按插入顺序移除
pollDog:将所有Dog按插入顺序移除
pollCat:将所有Cat按插入顺序移除
isEmpty:查看是否为空
isDogEmpty:查看Dog元素是否为空
isCatEmpty:查看Cat元素是否为空
父类Pet///
public class Pet{
private String type;
public Pet(String type) {
this.type = type;
}
public String getPet() {
return this.type;
}
}
/狗,继承Pet///
public class Dog extends Pet{
public Dog() {
super("dog");
}
}
猫,继承Pet
public class Cat extends Pet{
public Cat() {
super("cat");
}
}
其实还是考察自己定义类的能力。
思路:肯定要在这个大的队列中维护两个小队列,分别存Cat和Dog。但是如何记录每个元素的入队时间?就是要给每个Pet加上一个时间戳。所以我们要自己重写一个封装了Pet的新类,在Pet的基础上,加上时间戳,就是一个count。
public class newPet{
private Pet pet;
private long count;
public newPet(Pet pet,long count) { //封装类的构造函数中就要带有时间戳
this.pet = pet;
this.count = count;
}
public Pet getPet() { //要有接口来获取内部的属性值,因为都是private,单例模式??
return this.pet;
}
public long getCount() {
return this.count;
}
public String getPetType() {
return this.pet.getPetType();
}
}
封装好新类之后,就可以在最终的猫狗队列大类中,维护两个Queue了,内部存的都是这个新封装的,带时间戳的newPet
public class catdogQue{
private Queue<newPet> dogQ;
private Queue<newPet> catQ;
private long count; //注意此处count为全局变量,这样才会记录每一个的入队时间
public cardogQue() {
this.dogQ = new LinkedList<newPet>();
this.catQ = new LinkedList<newPet>();
this.count = 0;
}
public void add(Pet pet) { //注意,用户传入的依然是Pet原类型,要在内部自己重新生成newPet类型
if(pet.getPetType().equals("dog")) {
this.dogQ.add(new newPet(pet,this.count++));
}else if(pet.getPetType().equals("cat")) {
this.catQ.add(new newPet(pet,this.count++));
}else {
throw new RuntimeException("no cat or dog"); //防止输入类型有误
}
}
public Pet pollAll() {
if(!this.dogQ.isEmpty()&&!this.catQ.isEmpty()) { //若两个都不为空
if(this.dogQ.peek().getCount() < this.catQ.peek().getCount()) {
return this.dogQ.poll().getPet(); // 比较两个对列的头元素的count,即入队时间,谁小先poll谁
}else {
return this.catQ.poll().getPet();
}
}
else if(!this.dogQ.isEmpty()){ //若猫为空
return this.dogQ.poll().getPet();
}
else if(!this.catQ.isEmpty()) { //若狗为空
return this.catQ.poll().getPet();
}
else {
throw new RuntimeException("que is Empty");
}
}
public Dog pollDog() {
if(!this.isDogQueEmpty()) {
return (Dog) this.dogQ.poll().getPet();
}else {
throw new RuntimeException("dog que is Empty");
}
}
public Cat pollCat() {
if(!this.isCatQueEmpty()) {
return (Cat) this.catQ.poll().getPet();
}else {
throw new RuntimeException("cat que is Empty");
}
}
public boolean isEmpty() {
return this.dogQ.isEmpty()&&this.catQ.isEmpty();
}
public boolean isDogEmpty() {
return this.dogQ.isEmpty();
}
public boolean isCatEmpty() {
return this.catQ.isEmpty();
}
}