題目:
寵物,狗和貓的類如下:
public class Pet{ private String type; public Pet(String type){ this.type=type; } public String getPetType(){ return this.type; } } public class Dog extends Pet{ public Dog(){ super(“dog”); }
}
public class Cat extends Pet{ public Cat(){ super(“cat”); } } 實現一種狗貓隊列的結構,要求如下: 1. 用戶可以調用add方法將cat類或dog類的實例放入隊列中; 2.
用戶可以調用pollAlll方法,將隊列所有的實例按照進隊列的先後順序依次彈出; 3.用戶可以調用pollDog方法,將隊列中dog類的實例按照隊列的先後順序依次彈出; 4.用戶可以調用pollCat方法,將隊列中Cat類的實例按照隊列的先後順序依次彈出; 5.用戶可以調用isEmpty方法,檢查隊列中是否還有dog或cat的實例; 6.用戶可以調用isDogEmpty方法,檢查隊列中是否還有dog的實例;
7.用戶可以調用isCatEmpty方法,檢查隊列中是否還有cat的實例;
解法:
分別用兩個隊列保存cat和dog,並建立一個新類PetEnterQueue爲Cat和dog加入時間戳,好區分進入先後,並且不改變前面的類。然後在
隊列中加入實例時,如果是dog(cat)生成對應的PetEnterQueue實例。放入隊列中。彈出就判斷時間戳,count小的先出來
代碼如下:
package dogcatqueue;
public 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 String getEnterPetType(){
return pet.getPetType();
}
}
package dogcatqueue;
import java.util.LinkedList;
import java.util.Queue;
public class DogCatQueue {
private Queue<PetEnterQueue> dogQ;
private long count;
private Queue<PetEnterQueue> catQ;
public void DogCatQueue(){
dogQ = new LinkedList<PetEnterQueue>();
count =0;
catQ = new LinkedList<PetEnterQueue>();
}
//加入隊列,時間戳count++。
public void add(Pet pet){
if(pet.getPetType().equals("dog")){
dogQ.add(new PetEnterQueue(pet, count++));
}else if(pet.getPetType().equals("cat")){
catQ.add(new PetEnterQueue(pet,count++));
}else{
throw new RuntimeException("err");
}
}
//根據時間戳count大小從隊列中彈出
public Pet pollAll(){
if(!dogQ.isEmpty()&&!catQ.isEmpty()){
if(dogQ.peek().getCount()<catQ.peek().getCount()){
return dogQ.poll().getPet();
}else{
return catQ.poll().getPet();
}
}else if(!dogQ.isEmpty()){
return dogQ.poll().getPet();
}else if(!catQ.isEmpty()){
return catQ.poll().getPet();
}else{
throw new RuntimeException("err,queue is empty");
}
}
public Pet pollDog(){
if(!isDogQueueEmpty()){
return dogQ.poll().getPet();
}else{
throw new RuntimeException("err");
}
}
public Pet pollCat(){
if(!isCatQueueEmpty()){
return dogQ.poll().getPet();
}else{
throw new RuntimeException("err");
}
}
public boolean isEmpty(){
return dogQ.isEmpty()&&catQ.isEmpty();
}
public boolean isDogQueueEmpty(){
return dogQ.isEmpty();
}
public boolean isCatQueueEmpty(){
return catQ.isEmpty();
}
}
學習至左程雲老師《程序員代碼面試指南》