程序员代码面试指南读书笔记"/>
程序员代码面试指南读书笔记
问题描述:队列中的对象可能是狗,也可能是猫,popall pollcat polldog等
主要需要考虑的问题:记录入队列的时间
解题思路:
设计一个新类 ,添加一个count,用于记录add的顺序
package sharp1;import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;import javax.management.Query;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 需要考虑猫和狗哪个先进栈的
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 String getEnterPetType(){return this.pet.getPetType();}
}
public class CatAndDagQueue {private Queue<PetEnterQueue> dogQ;private Queue<PetEnterQueue> catQ;private long count;public CatAndDagQueue(){this.dogQ = new LinkedList<PetEnterQueue>();this.catQ = new LinkedList<PetEnterQueue>();this.count = 0;}public void add(Pet pet){if(pet.getPetType().equals("Dog")){dogQ.add(new PetEnterQueue(pet, this.count++));}else if(pet.getPetType().equals("Cat")){catQ.add(new PetEnterQueue(pet, this.count++)); }else{throw new RuntimeException("err,not dag or cat");}}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();}}if(!this.dogQ.isEmpty()){return this.dogQ.poll().getPet();}else if(!this.catQ.isEmpty()){return this.catQ.poll().getPet();}else {throw new RuntimeException("queue is queue");}}public boolean isDogQueueEmpty(){return this.dogQ.isEmpty();}public boolean isCatQueueEmpty(){return this.catQ.isEmpty();}public Dog pollDog(){if(!this.isDogQueueEmpty()){return (Dog)this.dogQ.poll().getPet();}else {throw new RuntimeException("dog queue is empty");} }public Cat pollCat(){if(!this.isCatQueueEmpty()){return (Cat)this.catQ.poll().getPet();}else {throw new RuntimeException("cat queue is empty");}}}
更多推荐
程序员代码面试指南读书笔记
发布评论