-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDogCatQueue.java
125 lines (104 loc) · 2.86 KB
/
DogCatQueue.java
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package stack_and_queue;
import java.util.LinkedList;
import java.util.Queue;
/**
* @Author: Wenhang Chen
* @Description:实现一个可以存储猫和狗的队列,其中poll相关操作需要将指定类型按序弹出
* @Date: Created in 15:31 10/29/2019
* @Modified by:
*/
public class DogCatQueue {
private Queue<PetItem> dogQ;
private Queue<PetItem> catQ;
// 用count记录先后次序,新建类PetItem,存储时
// 将pet和count作为一个整体一并存入队列
private long count;
public DogCatQueue() {
this.dogQ = new LinkedList<PetItem>();
this.catQ = new LinkedList<PetItem>();
this.count = 0;
}
public void add(Pet pet) {
if (pet.getType().equals("dog")) {
this.dogQ.add(new PetItem(pet, this.count++));
} else if (pet.getType().equals("cat")) {
this.catQ.add(new PetItem(pet, this.count++));
} else {
throw new RuntimeException("Error, not cat or dog");
}
}
public Pet pollAll() {
if (!dogQ.isEmpty() && !catQ.isEmpty()) {
if (dogQ.peek().getCount() < 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("Error, queue is empty");
}
}
public Dog pollDog() {
if (!this.dogQ.isEmpty()) {
return (Dog) this.dogQ.poll().getPet();
} else {
throw new RuntimeException("DogQueue is empty");
}
}
public Cat pollCat() {
if (!this.catQ.isEmpty()) {
return (Cat) this.catQ.poll().getPet();
} else {
throw new RuntimeException("CatQueue is empty");
}
}
public boolean isEmpty() {
return this.dogQ.isEmpty() && this.catQ.isEmpty();
}
public boolean isDogQueueEmpty() {
return this.dogQ.isEmpty();
}
public boolean isCatQueueEmpty() {
return this.catQ.isEmpty();
}
}
class PetItem {
private Pet pet;
private long count;
public PetItem(Pet pet, long count) {
this.pet = pet;
this.count = count;
}
public Pet getPet() {
return pet;
}
public long getCount() {
return count;
}
public String getPetItemType() {
return this.pet.getType();
}
}
class Pet {
private String type;
public Pet(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
}
class Dog extends Pet {
public Dog() {
super("dog");
}
}
class Cat extends Pet {
public Cat() {
super("cat");
}
}