def test_DoublyLinkedList___repr__(self):
        l1 = DoublyLinkedList()
        l1.insert(0)
        l1.insert(1)
        l1.insert(2)

        self.assertEquals(l1.__repr__(), "(2, 1, 0)")
Пример #2
0
class RingBuffer:
    def __init__(self, capacity):
        self.capacity = capacity
        self.current = None  # what's going to be overwritten
        self.storage = DoublyLinkedList()

    def __repr__(self):
        return self.storage.__repr__()

    def append(self, item):
        # if empty, set the current to the head
        if self.storage.length == 0:
            self.storage.add_to_tail(item)
            self.current = self.storage.head
        # if less than capcacity, link the tail to head after adding
        elif self.storage.length < self.capacity:
            self.storage.add_to_tail(item)
            self.storage.tail.next = self.storage.head
        # otherwise, overwrite the oldest, and move the oldest to next item
        # since tail is linked to head, this works fine
        else:
            self.current.value = item
            self.current = self.current.next

    def get(self):
        # Note:  This is the only [] allowed
        list_buffer_contents = []
        current = self.storage.head
        while current is not self.storage.tail:
            list_buffer_contents.append(current.value)
            current = current.next

        list_buffer_contents.append(self.storage.tail.value)

        return list_buffer_contents
Пример #3
0
class Stack:
    def __init__(self):
        self.size = 0
        # Why is our DLL a good choice to store our elements?
        # a lot of insertion at the head and then
        self.storage = DoublyLinkedList()

    def __repr__(self):
        return self.storage.__repr__()

    def push(self, value):
        self.size += 1
        return self.storage.add_to_tail(value)

    def pop(self):
        self.size -= 1
        return self.storage.remove_from_tail()

    def len(self):
        return self.storage.length