[程序源代码面试指南第二版] 猫狗队列
原有结构
猫狗猫狗
class Pet{
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Pet(String type) {
this.type = type;
}
}
class Dog extends Pet{
public Dog() {
super("dog");
}
}
class Cat extends Pet{
public Cat() {
super("cat");
}
}
需求
实现队列可以存放猫狗,并且需要根据存入先后顺序依次弹出
分别实现:
- add 猫狗进队列
- pollAdd 先后顺序出猫狗
- pollDog 先后顺序出狗
- pollCat 先后顺序出猫
- isEmpty 是否有猫狗
- isDogEmpty
- isCatEmpty
几种问题
- 哈希表实现 出现问题,一个实例不能支持多次进队列
- CAT队列放cat实例,DOG队列放dog实例总队列再放全部实例 出现问题,总队列更新问题
- cat及dog加时间戳 出现问题,不能修改原有结构
主要思路
时间戳实现先后顺序弹出,但是不能修改原有结构。因此新建一个类(关键点其实就是时间戳)
class PetEnterQueue{
// 用户原有的实例
private Pet pet;
// 这个实例的时间戳
private long count;
public PetEnterQueue(Pet pet, long count) {
this.pet = pet;
this.count = count;
}
public Pet getPet() {
return pet;
}
public void setPet(Pet pet) {
this.pet = pet;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
}
附件
代码
public class whatwhat{
Queue<Pet> queue_pet = new ArrayDeque();private Queue<PetEnterQueue> dogQ;
private Queue<PetEnterQueue> catQ;
private long count;
public QUEUE_DOGCAT() {
this.dogQ = new LinkedList<PetEnterQueue>();
this.catQ = new LinkedList<PetEnterQueue>();
this.count = 0;
}
public void add(Pet whatpet){
if("dog".equals(whatpet.getType())){
this.dogQ.add(new PetEnterQueue(whatpet, this.count++));
}else if("cat".equals(whatpet.getType())){
this.catQ.add(new PetEnterQueue(whatpet, this.count++));
}else {
throw new RuntimeException("error, not dog not cat");
}
}
// 主要根据时间戳count
public Pet pollAll(){
//如果队列都不为空
if(!this.dogQ.isEmpty() && !this.catQ.isEmpty()){
if(this.dogQ.peek().getCount() < this.catQ.peek().getCount()){
return this.dogQ.poll().getPet();
}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("queue_pet empty");
}
}
// 主要弹出狗狗
public Dog pollDog(){
//如果队列都不为空
if(!this.dogQ.isEmpty()){
return (Dog) this.dogQ.poll().getPet();
}else {
throw new RuntimeException("queue_pet empty");
}
}
// 主要弹出狗狗
public Cat pollCat(){
//如果队列都不为空
if(!this.catQ.isEmpty()){
return (Cat) this.catQ.poll().getPet();
}else {
throw new RuntimeException("queue_pet empty");
}
}
public boolean isEmpty(){
return this.dogQ.isEmpty()&&this.catQ.isEmpty();
}
public boolean isDogQueueEmpty(){
return this.dogQ.isEmpty();
}
public boolean isCatQueueEmpty(){
return this.catQ.isEmpty();
}
}