猫狗队列

    xiaoxiao2024-10-14  91

    题目描述

    实现一种猫狗队列 可以add,pollAll,pollDog,pollCat,isEmpty,isDogEmpty,isCatEmpty 要求如下:

    用户可以调用add方法将cat类或者dog类的实例放入队列中;用户可以调用pollAll方法,将队列中所有的实例按照队列的先后顺序依次弹出;用户可以调用pollDog方法,将队列中dog类的实例按照队列的先后顺序依次弹出;用户可以调用pollCat方法,将队列中cat类的实例按照队列的先后顺序依次弹出;用户可以调用isEmpty方法,检查队列中是否还有dog和cat的实例;用户可以调用isDogEmpty方法,检查队列中是否还有do的实例;用户可以调用isCatEmpty方法,检查队列中是否还有cat的实例。

    解题思路

    构建猫和狗两个队列,设计一个类PetEnterQueue ,用于记录放入队列的每个元素的时间戳,取出时按时间戳来判断从dog队列或cat队列取出元素

    代码

    package TestNode.StackAndQueue; import java.util.LinkedList; import java.util.Queue; public class CatDogQueue { public static class Pet{ private String type; public Pet(String type){ this.type = type; } public String getType() { return type; } } public static class Cat extends Pet{ public Cat(){ super("Cat"); } } public static class Dog extends Pet{ public Dog(){ super("Dog"); } } /*先定义一个新类可以记录入队时间*/ public static class PetEnterQueue{ private Pet pet; private long count; public PetEnterQueue(Pet pet, long count){ this.pet = pet; this.count = count; } public long getCount() { return count; } public Pet getPet() { return pet; } public String getEnterPetType(){ return pet.getType(); } } private Queue<PetEnterQueue> dogQueue; private Queue<PetEnterQueue> catQueue; private long count; public CatDogQueue(){ dogQueue = new LinkedList<>(); catQueue = new LinkedList<>(); count = 0; } public void add(Pet pet){ if (pet.getType().equals("Dog")){ this.dogQueue.add(new PetEnterQueue(pet, count++)); }else if (pet.getType().equals("Cat")){ this.catQueue.add(new PetEnterQueue(pet, count++)); }else { throw new RuntimeException("err, not dog or cat"); } } public Pet pollAll(){ if (!this.dogQueue.isEmpty() && !this.catQueue.isEmpty()){ if (this.dogQueue.peek().getCount() < this.catQueue.peek().getCount()){ return this.dogQueue.poll().getPet(); }else { return this.catQueue.poll().getPet(); } }else if (!this.dogQueue.isEmpty()){ return dogQueue.poll().getPet(); }else if (!this.dogQueue.isEmpty()){ return this.catQueue.poll().getPet(); }else { throw new RuntimeException("err, queue is empty"); } } public Dog pollDog() { if (!isDogEmpty()) { return (Dog) this.dogQueue.poll().getPet(); } else { throw new RuntimeException("err,dog queue is empty"); } } public Cat pollCat() { if (!isCatEmpty()) { return (Cat) this.catQueue.poll().getPet(); } else { throw new RuntimeException("err,cat queue is empty"); } } public boolean isEmpty() { return this.dogQueue.isEmpty() && this.catQueue.isEmpty(); } public boolean isDogEmpty() { return this.dogQueue.isEmpty(); } public boolean isCatEmpty() { return this.catQueue.isEmpty(); } }
    最新回复(0)