コード例 #1
0
class StackLinkedList:
    """
        This is a Linked List based implementation of a stack
    """

    # Creates an empty list with Linked List
    def __init__(self):
        self._items = SinglyLinkedList()

    # Returns True if stack is Empty otherwise returns False
    def isEmpty(self):
        return self._items.node_counter == 0

    def __len__(self):
        return self._items.node_counter

    # Returns the top item of the stack without removing it
    def peek(self):
        assert not self.isEmpty(), "Cannot peek at an empty stack"
        return self._items.get_head()

    # Remove and return the last item of the stack
    def pop(self):
        assert not self.isEmpty(), "Cannot pop from an empty stack"
        last_item = self.peek()
        self._items.delete_start()
        return last_item

    # Push an item at the top of the stack
    def push(self, item):
        self._items.insert_start(item)