首页 > 其他 > 详细

栈--猫狗队列

时间:2020-04-27 23:27:17      阅读:71      评论:0      收藏:0      [点我收藏+]

题目

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();
    }
}

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

栈--猫狗队列

原文:https://www.cnblogs.com/swifthao/p/12790681.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!