-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDogCatQueue.java
More file actions
92 lines (80 loc) · 1.98 KB
/
DogCatQueue.java
File metadata and controls
92 lines (80 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package pet;
import java.util.LinkedList;
import java.util.Queue;
/**
* @Date 2016年7月26日20:04:54
*
* @author shadow
*
*/
public class DogCatQueue {
private Queue<PetEnterQueue> dogQ;
private Queue<PetEnterQueue> catQ;
private long count;
public DogCatQueue(){
dogQ = new LinkedList<>();
catQ = new LinkedList<>();
this.count = 0;
}
public void add(Pet pet){
if(pet.getType().equals("dog")){
this.dogQ.add(new PetEnterQueue(pet, this.count++));
}else if(pet.getType().equals("cat")){
this.catQ.add(new PetEnterQueue(pet, this.count++));
}else {
throw new RuntimeException("err, not dog or cat.");
}
}
public Pet pollAll(){
if(!this.dogQ.isEmpty() && !this.catQ.isEmpty()){
if(this.dogQ.peek().getCount() < this.catQ.peek().getCount()){
return this.dogQ.poll().getPet();
}else{
return this.catQ.poll().getPet();
}
}else if(!this.dogQ.isEmpty()){
return this.dogQ.poll().getPet();
}else if(!this.catQ.isEmpty()){
return this.catQ.poll().getPet();
}else {
throw new RuntimeException("err, queue is empty.");
}
}
public Dog pollDog(){
if(this.dogQ.isEmpty()){
throw new RuntimeException("Dog queue is empty.");
}else{
return (Dog) this.dogQ.poll().getPet();
}
}
public Cat pollCat(){
if(this.catQ.isEmpty()){
throw new RuntimeException("Cat queue is empty.");
}else{
return (Cat) this.dogQ.poll().getPet();
}
}
public boolean isEmpty(){
return this.dogQ.isEmpty() && this.dogQ.isEmpty();
}
public boolean isDogQueueEmpty(){
return this.dogQ.isEmpty();
}
public boolean isCatQueueEmpty(){
return this.catQ.isEmpty();
}
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
Dog dog2 = new Dog();
DogCatQueue queue = new DogCatQueue();
queue.add(cat);
queue.add(dog);
queue.add(cat);
queue.add(dog2);
for(int i = 0; i < queue.count; i++){
System.err.println(queue.pollAll().getType());
}
System.err.println(queue.pollCat());
}
}