实现一种猫狗队列的结构,要求如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLOutput;
import java.util.LinkedList;
import java.util.Queue;
class Dog{
public String name;
public int order;// 入队顺序
// 初始化函数
public Dog(String name,int order)
{
this.name = name;
this.order = order;
}
}
class Cat{
public String name;
public int order;// 入队顺序
public Cat(String name,int order)
{
this.name = name;
this.order = order;
}
}
class CatDogQueue{
public Queue<Cat> catQueue = new LinkedList<>();
public Queue<Dog> dogQueue = new LinkedList<>();
private int order = 0;// 入队顺序编号
public CatDogQueue()
{
// 初始化函数
catQueue = new LinkedList<>();
dogQueue = new LinkedList<>();
}
// 入队的时候一定要添加入队顺序
public void add(String animal,String id)
{
// 将cat类或者dog类的实例 放入队列中
if(animal.equals("cat"))
{
// 将猫实例放入猫队列中
catQueue.offer(new Cat(animal + " " + id,order));//
order++;
}
if(animal.equals("dog"))
{
// 将狗实例 送入狗队列中
dogQueue.offer(new Dog(animal + " " + id,order));
order++;
}
}
// 判断队列是否为空
public String isEmpty()
{
// 猫狗队列都为空 才是空
return catQueue.isEmpty() && dogQueue.isEmpty()?"yes":"no";
}
// 判断猫队列是否为空
public String isCatEmpty()
{
return catQueue.isEmpty()?"yes":"no";
}
// 判断狗队列是个否为空
public String isDogEmpty()
{
return dogQueue.isEmpty()?"yes":"no";
}
// 出队操作
public String poll()
{
// 首先判断队列是否为空
if(!catQueue.isEmpty() && !dogQueue.isEmpty())
{
// 比较一下猫队列和狗队列 队头元素的入队顺序 顺序小的先出队
if(catQueue.peek().order < dogQueue.peek().order)
{
return pollCat();
}
else {
return pollDog();
}
}
else if(!catQueue.isEmpty())
{
return pollCat();
}
else if(!dogQueue.isEmpty())
{
return pollDog();
}
else {
return "";
}
}
// 猫出队
public String pollCat(){
return catQueue.poll().name;
}
// 狗出队
public String pollDog(){
return dogQueue.poll().name;
}
}
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
CatDogQueue queue = new CatDogQueue();
for(int i = 0; i < n; i++)
{
String[] params = br.readLine().trim().split(" ");// 按照空格分割
if(params[0].equals("add"))
{
queue.add(params[1],params[2]);
}
else if(params[0].equals("pollAll"))
{
while(queue.isEmpty().equals("no"))
{
System.out.println(queue.poll());
}
}
else if(params[0].equals("pollCat"))
{
while(queue.isCatEmpty().equals("no"))
{
System.out.println(queue.pollCat());
}
}
else if(params[0].equals("pollDog"))
{
while(queue.isDogEmpty().equals("no"))
{
System.out.println(queue.pollDog());
}
}
else if(params[0].equals("isEmpty"))
{
System.out.println(queue.isEmpty());
}
else if(params[0].equals("isCatEmpty"))
{
System.out.println(queue.isCatEmpty());
}
else if(params[0].equals("isDogEmpty"))
{
System.out.println(queue.isDogEmpty());
}
}
}
}