由于我对C++面向对象的内容还不太熟,所以这道题直接从网上搜了答案,并且没有配测试用例,随后会再更新。
//★题目:猫狗队列
//要求:宠物、狗和猫的类如下:
// class Pet {
// string type;
// public:
// Pet(string type) {
// this->type = type;
// }
// string getPetType() {
// return this->type;
// }
// };
//
// class Dog :public Pet {
// public:
// Dog() :Pet("Dog") {}
// };
//
// class Cat :public Pet {
// public:
// Cat() : Pet("Cat") {}
// };
// 设计一个猫狗队列的结构,要求如下:
// 用户可以调用add方法,将cat类或dog类的实例放入队列中
// 用户可以调用pollAll方法,将队列中所有实例按照进队列对先后顺序依次弹出
// 用户可以调用pollDog方法,将dog类中的实例按照进队列对先后顺序依次弹出
// 用户可以调用pollCat方法,将cat类中的实例按照进队列对先后顺序依次弹出
// 用户可以调用isEmpyt方法,检查队列中是否还有dog或cat的实例
// 用户可以调用isDogEmpyt方法,检查队列中是否还有dog类的实例
// 用户可以调用isCatEmpyt方法,检查队列中是否还有cat类的实例
#include <queue>
using namespace std;
class Pet {
string type;
public:
Pet(string type) {
this->type = type;
}
string getPetType() {
return this->type;
}
};
class Dog :public Pet {
public:
Dog() :Pet("Dog") {}
};
class Cat :public Pet {
public:
Cat() : Pet("Cat") {}
};
class PetCount {
Pet* pet;
int count;
public:
PetCount(Pet* pet, int cnt) {
this->pet = pet;
this->count = cnt;
}
Pet* getPet() {
return pet;
}
int getCount() {
return this->count;
}
string getPetType() {
return pet->getPetType();
}
};
class DogCatQueue {
queue<PetCount>catq;
queue<PetCount>dogq;
int count;
public:
DogCatQueue() :count(0) {}
void add(Dog &d) {
dogq.push(PetCount(&d, count++));
}
void add(Cat &c) {
catq.push(PetCount(&c, count++));
}
bool empty() {
return dogq.empty() && catq.empty();
}
bool DogEmpty() { return dogq.empty(); }
bool CatEmpty() { return catq.empty(); }
Cat *pollCat() {
Cat* r = static_cast<Cat*>(catq.front().getPet());
catq.pop();
return r;
}
Dog *pollDog() {
Dog*r = static_cast<Dog*>(dogq.front().getPet());
dogq.pop();
return r;
}
Pet* pollAll() {
if (empty())return nullptr;
else if (DogEmpty())return pollCat();
else if (CatEmpty())return pollDog();
return (dogq.front().getCount() > catq.front().getCount()) ? (Pet*)pollDog() : (Pet*)pollCat();
}
};
int main()
{
system("pause");
return 0;
}