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
| class AnimalShelf { public: AnimalShelf() : head(new Node()), tail(new Node()) { head->next = tail; tail->prev = head; } void enqueue(vector<int> animal) { push(animal[0], animal[1]); } vector<int> dequeueAny() { if(tail->prev == head) return {-1, -1}; vector<int> ret{tail->prev->num, tail->prev->type}; deleteNode(tail->prev); return ret; } vector<int> dequeueDog() { auto ret = pop(1); if(ret == -1) return {-1, -1}; return {ret, 1}; } vector<int> dequeueCat() { auto ret = pop(0); if(ret == -1) return {-1, -1}; return {ret, 0}; } private: struct Node { Node* next; Node* prev; int num = 0; int type; Node() = default; Node(Node* next, Node* prev, int num, int type) : next(next), prev(prev), num(num), type(type) {}; }; Node *head, *tail; void push(int num, int type) { auto next = head->next; head->next = new Node(head->next, head, num, type); next->prev = head->next; } int pop(int type) { auto point = tail->prev; while(point != head) { if(point->type == type) { auto ret = point->num; deleteNode(point); return ret; } point = point->prev; } return -1; } void deleteNode(Node* node) { auto tmp = node; node->prev->next = node->next; node->next->prev = node->prev; delete tmp; } };
|