Пример #1
0
class AnimalShelter:
    def __init__(self):
        self.cats = LinkedList([])
        self.dogs = LinkedList([])
        self.__stamp = 0

    def enqueue(self, animal: Animal):
        animal.timestamp = self.__stamp
        self.__stamp += 1

        if isinstance(animal, Cat):
            self.cats.append(animal)
        else:
            self.dogs.append(animal)

    def dequeue_any(self):
        if self.cats.head == None:
            return self.dequeue_dog()
        elif self.dogs.head == None:
            return self.dequeue_cat()

        dog = self.dogs.head.data
        cat = self.cats.head.data
        if (dog > cat):
            return self.dequeue_dog()
        else:
            return self.dequeue_cat()

    def dequeue_dog(self):
        if self.dogs.head == None:
            raise Exception()

        tmp = self.dogs.head.data
        self.dogs.head = self.dogs.head.next
        return tmp

    def dequeue_cat(self):
        if self.cats.head == None:
            raise Exception()

        tmp = self.cats.head.data
        self.cats.head = self.cats.head.next
        return tmp
Пример #2
0
class SimpleAnimalShelter:
    CAT = 1
    DOG = 2

    def __init__(self):
        self.list = LinkedList([])

    def enqueue(self, animal):
        self.list.append(animal)

    def dequeue(self):
        oldest = self.list.head
        if oldest == None:
            raise Exception()
        self.list.head = self.list.head.next
        return oldest

    def dequeue_cat(self):
        return self.__dequeue_animal(SimpleAnimalShelter.CAT)

    def dequeue_dog(self):
        return self.__dequeue_animal(SimpleAnimalShelter.DOG)

    def __dequeue_animal(self, animal):
        if self.list.head == None:
            raise Exception()
        elif self.list.head.data == animal:
            tmp = self.list.head
            self.list.head = self.list.head.next
            return tmp

        oldest = None
        n = self.list.head
        while n.next != None and n.next.data != animal:
            n = n.next
        if n.next == None:
            raise Exception()

        oldest = n.next
        n.next = n.next.next
        return oldest
def gen_depth_list(root):
    if not root:
        return []

    q: queue.Queue = queue.Queue()
    q.put(root)
    lst = []
    current = LinkedList([root])

    while len(current) > 0:
        lst.append(current)
        parents = current
        current = LinkedList([])

        for parent in parents:
            if parent.left:
                current.append(parent.left)
            if parent.right:
                current.append(parent.right)

    return lst