栈--猫狗队列

题目

public class Pet {
    private String type;
    public Pet(String type){
        this.type = type;
    }
    public String getPetType(){
        return this.type;
    }
}
public class Cat extends Pet{
    public Cat() {
        super("Cat");
    }
}
public class Dog extends Pet{
    public Dog(){
        super("Dog");
    }
}

要求:

  • add可以将dog类 cat类示例加入队列中
  • pollAll
  • pollDog
  • pollCat
  • isEmpty
  • isDogEmpty
  • isCatEmpty

解答

将不同示例盖上时间戳,但是又不修改原有类,定义一个新类:PetEnterQueue

核心:添加计数器!!!

public class PetEnterQueue {
    private Pet pet;
    private int count;

    public PetEnterQueue(Pet pet,int count){
        this.pet = pet;
        this.count = count;
    }

    public Pet getPet(){
        return this.pet;
    }

    public int getCount(){
        return this.count;
    }

    public String getEnterPetType(){
        return this.pet.getPetType();
    }

}

队列实现如下:

public class DogCatQueue {
    private Queue<PetEnterQueue> dogQ;
    private Queue<PetEnterQueue> catQ;
    private int count;
    public DogCatQueue(){
        dogQ = new LinkedList<PetEnterQueue>();
        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("error");
        }
    }
    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("empty queue");
        }
    }
    public Dog pollDog(){
        if(!dogQ.isEmpty()){
            return (Dog) dogQ.poll().getPet();
        }else {
            throw new RuntimeException("empty dog");
        }
    }
    public Cat pollCat(){
        if(!catQ.isEmpty()){
            return (Cat) catQ.poll().getPet();
        }else {
            throw new RuntimeException("empty cat");
        }
    }
    public boolean isEmpty(){
        return dogQ.isEmpty()&&catQ.isEmpty();
    }
    public boolean isDogEmpty(){
        return dogQ.isEmpty();
    }
    public boolean isCatEmpty(){
        return catQ.isEmpty();
    }
}

出处:《程序员代码面试指南》

猜你喜欢

转载自www.cnblogs.com/swifthao/p/12790681.html
今日推荐