程序员代码面试指南--猫狗队列
程序员文章站
2024-02-27 16:11:39
...
/**
猫狗队列
【题目】
实现一种狗猫队列的结构,要求如下:
用户可以调用add方法将cat类或dog类的实例放入队列中;
用户可以调用pollAll方法,将队列中所有的实例按照进队列的先后顺序依次弹出;
用户可以调用pollDog方法,将队列中dog类的实例按照进队列的先后顺序依次弹出;
用户可以调用pollCat方法,将队列中cat类的实例按照进队列的先后顺序依次弹出;
用户可以调用isEmpty方法,检查队列中是否还有dog或cat的实例;
用户可以调用isDogEmpty方法,检查队列中是否有dog类的实例;
用户可以调用isCatEmpty方法,检查队列中是否有cat类的实例。
*/
import java.util.LinkedList;
import java.util.Queue;
public class C04_DogCatQueue {
public static void main(String[] args) {
DogCatQ test = new DogCatQ();
Pet dog1 = new Dog();
Pet cat1 = new Cat();
Pet dog2 = new Dog();
Pet cat2 = new Cat();
Pet dog3 = new Dog();
Pet cat3 = new Cat();
test.add(dog1);
test.add(cat1);
test.add(dog2);
test.add(cat2);
test.add(dog3);
test.add(cat3);
test.add(dog1);
test.add(cat1);
test.add(dog2);
test.add(cat2);
test.add(dog3);
test.add(cat3);
// test.pollAll();
// System.out.println(test.isEmpty());
while (!test.isDogQueueEmpty()) {
System.out.println(test.pollDog().getPetType());
}
}
///////////////////题目给定的三个类///////////////////////////
public static class Pet {
private String type;
public Pet(String type) {
this.type = type;
}
public String getPetType() {//类型
return this.type;
}
}
public static class Dog extends Pet {
public Dog() {
super("dog");
}
}
public static class Cat extends Pet {
public Cat() {
super("cat");
}
}
///////////////////我的队列////////////////////////////
public static class petEnterQueue{
private Pet pet;
private int count;
public petEnterQueue(Pet pet,int count) {
this.pet = pet;
this.count = count;
}
public Pet getPet() {
return pet;
}
public int getCount() {
return count;
}
public String getPetType(){
return pet.getPetType();
}
}
public static class DogCatQ{
private Queue<petEnterQueue> dogQ;
private Queue<petEnterQueue> catQ;
private int count;
public DogCatQ(){
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, count++));
}else if(pet.getPetType().equals("cat")){
catQ.add(new petEnterQueue(pet, count++));
} else {
throw new RuntimeException("type erroe,not dog or cat");
}
}
public void pollAll(){
while(!isEmpty()){
if(!dogQ.isEmpty() && !catQ.isEmpty()){
//猫狗队列都不为空的时候
if(dogQ.peek().getCount()>catQ.peek().getCount()){
dogQ.poll();
}else {
catQ.poll();
}
}else if(!dogQ.isEmpty()){
dogQ.poll();
}else if(!catQ.isEmpty()){
catQ.poll();
}
}
}
public Dog pollDog() {
if(!isDogQueueEmpty()){
return (Dog) dogQ.poll().getPet();
}
throw new RuntimeException("Dog queue is empty!");
}
public Cat pollCat() {
if(!isCatQueueEmpty()){
return (Cat) catQ.peek().getPet();
}
throw new RuntimeException("Cat queue is empty!");
}
public boolean isEmpty() {//队列是否为空
return catQ.isEmpty() && dogQ.isEmpty();
}
public boolean isDogQueueEmpty() {
return dogQ.isEmpty();
}
public boolean isCatQueueEmpty() {
return catQ.isEmpty();
}
}
}
上一篇: Linux下创建、删除软链接
下一篇: Linux struct stat介绍