30 lines
2.2 KiB
Markdown
30 lines
2.2 KiB
Markdown
# 3.6. Animal shelter
|
|
|
|
> An animal shelter, which holds only dogs and cats, operates on a strictly"first in, first out" basis. People must adopt either the"oldest" (based on arrival time) of all animals at the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot select which specific animal they would like. Create the data structures to maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog, and dequeueCat. You may use the built-in Linkedlist data structure
|
|
|
|
## First idea
|
|
|
|
Functions I need:
|
|
|
|
* enqueue
|
|
* dequeueAny
|
|
* dequeueDog
|
|
* dequeueCat
|
|
|
|
Make a LinkedList, enqueue is just appendtoTail, dequeueAny is return top.data, and for dogs and cats, brute force option is just have a boolean attribute isDog or isCat, and iterate until we find the one we want.
|
|
|
|
More efficient way, we can make 2 other LinkedLists, with dogs and cats. so topDog.next is the next dog. Whenever a new animal enters the shelter, either the LinkDog or LinkCat points to the new animal, and when some animal is dequeued, the top of the general list and the top of the animal list get updated.
|
|
|
|
## Hints
|
|
|
|
* One idea is to have separate list for dogs and cats and then iterate through them to find the first dog/cat, what is the impact of doing this?
|
|
* the problem comes with `dequeueAny`, how do we know which dog or cat comes first. Either have another LinkedList with them ordered, or another attribute with the order and check which index/number is smallest.
|
|
* If we keep separate lists for each animal, how to find the oldest animal of any type?
|
|
* either new variable in list with index, or another linkedlist altogether
|
|
* Think of real life, where you have a list of dogs in chronological order and same with cats. What data do you need to find the oldest animal? How do you maintain this data?
|
|
* The entry date, when the animals came in. This is equivalent to an index
|
|
|
|
## Solution
|
|
|
|
Make the class `Dog` and `Cat`, which inherit from `Animal`, and keep an order (index). [Code in Github](https://github.com/careercup/CtCI-6th-Edition/tree/master/Java/Ch%2003.%20Stacks%20and%20Queues/Q3_06_Animal_Shelter)
|