0%

猫狗队列

题目

实现一个猫狗队列

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

// 宠物类
public class Pet {

private String mType;

public Pet(String type) {
mType = type;
}

public String getType() {
return mType;
}
}

// 狗
public class Dog extends Pet {

public Dog(String type) {
super(type);
}
}

// 喵
public class Cat extends Pet {

public Cat(String type) {
super(type);
}
}

实现一种猫狗队列的结构,要求:

  • add 方法将 cat 或者 dog 放入到队列中

  • pollAll 方法将队列中所有的实例按照入队的先后顺序依次弹出

  • pollCat 方法将队列中的 cat 按照入队先后顺序依次弹出

  • pollDog 方法将队列中的 dog 按照入队先后顺序依次弹出

  • isEmpty 方法检查队列中是否还有 dog 或者 cat 的实例

  • isCatQueueEmpty 方法检查 cat 队列是否还有 cat

  • isDogQueueEmpty 方法检查 dog 队列是否还有 dog

实现

使用组合,增加一个时间戳的字段

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

public class PetWithTimestamp {

private Pet mPet;

private long mTimestamp;

public PetWithTimestamp(Pet pet, long timestamp) {
mPet = pet;
mTimestamp = timestamp;
}

public Pet getPet() {
return mPet;
}

public long getTimestamp() {
return mTimestamp;
}

public String getType() {
return mPet.getType();
}
}

CatDogQueue 类设计

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

public class CatDogQueue {

private Queue<PetWithTimestamp> mCatQueue;

private Queue<PetWithTimestamp> mDogQueue;


public CatDogQueue() {
mCatQueue = new LinkedList<>();
mDogQueue = new LinkedList<>();
}

public void add(Pet pet) {

if (pet == null) {
throw new IllegalArgumentException("pet can't be null");
}

switch (pet.getType()) {

case "cat":
mCatQueue.add(new PetWithTimestamp(pet, System.currentTimeMillis()));
break;

case "dog":
mDogQueue.add(new PetWithTimestamp(pet, System.currentTimeMillis()));
break;

default:
break;
}
}

public Pet pollAll() {

if (!mCatQueue.isEmpty() && !mDogQueue.isEmpty()) {

if (mCatQueue.peek().getTimestamp() < mDogQueue.peek().getTimestamp()) {
return mCatQueue.poll().getPet();
} else {
return mDogQueue.poll().getPet();
}

} else if (!mCatQueue.isEmpty()) {

return mCatQueue.poll().getPet();

} else if (!mDogQueue.isEmpty()) {

return mDogQueue.poll().getPet();

} else {
throw new IllegalStateException("queue is empty!");
}
}

public Cat pollCat() {
if (!mCatQueue.isEmpty()) {
return (Cat) mCatQueue.poll().getPet();
} else {
throw new IllegalStateException("dog queue is empty!");
}
}

public Dog pollDog() {
if (!mDogQueue.isEmpty()) {
return (Dog) mDogQueue.poll().getPet();
} else {
throw new IllegalStateException("dog queue is empty!");
}
}

public boolean isEmpty() {
return mCatQueue.isEmpty() && mCatQueue.isEmpty();
}

public boolean isCatQueueEmpty() {
return mCatQueue.isEmpty();
}

public boolean isDogQueueEmpty() {
return mDogQueue.isEmpty();
}

}