1
+ """
2
+ An animal shelter, which holds only dogs and cats, operates on a strictly "first in, first out" basis. People must adopt
3
+ either the "oldest" (based on arrival time) of all animals at the shelter, or they can select whether they would prefer a
4
+ dog or a cat (receive the oldest animal of that type). They cannot select which specific animal they would like.
5
+ Create the data structures to maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog, and
6
+ dequeueCat. You may use the built-in LinkedList data structure.
7
+ """
8
+ class Animal :
9
+ def __init__ (self , animalName = None , animalType = None ):
10
+ self .animalName = animalName
11
+ self .animalType = animalType
12
+ self .next = None
13
+ self .timestamp = 0
14
+
15
+ class AnimalShelter :
16
+ def __init__ (self ):
17
+ self .headCat = None
18
+ self .tailCat = None
19
+ self .headDog = None
20
+ self .tailDog = None
21
+ self .order = 0
22
+
23
+ def enqueue (self , animalName , animalType ):
24
+ self .order += 1
25
+ newAnimal = Animal (animalName , animalType )
26
+ newAnimal .timestamp = self .order
27
+
28
+ if animalType == 'cat' :
29
+ if not self .headCat :
30
+ self .headCat = newAnimal
31
+ if self .tailCat :
32
+ self .tailCat .next = newAnimal
33
+ self .tailCat = newAnimal
34
+
35
+ elif animalType == 'dog' :
36
+ if not self .headDog :
37
+ self .headDog = newAnimal
38
+ if self .tailDog :
39
+ self .tailDog .next = newAnimal
40
+ self .tailDog = newAnimal
41
+
42
+ def dequeueCat (self ):
43
+ if self .headCat :
44
+ newAnimal = self .headCat
45
+ self .headCat = newAnimal .next
46
+ return str (newAnimal .animalName )
47
+ else :
48
+ return "No cat left!"
49
+
50
+ def dequeueDog (self ):
51
+ if self .headDog :
52
+ newAnimal = self .headDog
53
+ self .headDog = newAnimal .next
54
+ return str (newAnimal .animalName )
55
+ else :
56
+ return "No dog left!"
57
+
58
+ def dequeueAny (self ):
59
+ if self .headCat and not self .headDog :
60
+ return self .dequeueCat ()
61
+ elif not self .headCat and self .headDog :
62
+ return self .dequeueDog ()
63
+ elif self .headCat :
64
+ if self .headCat .timestamp < self .headDog .timestamp :
65
+ return self .dequeueCat ()
66
+ else :
67
+ return self .dequeueDog ()
68
+ else :
69
+ return "No animal left!"
0 commit comments