将键入提示添加到链表的顶部方法

时间:2018-12-20 07:32:47

标签: python linked-list

我正在学习用Python实现的链表:

$ cat linked_stack.py 
class LinkedStack:
    """LIFO Stack implementation using a singly linked list for storage"""
    #-------------nested Node class ------------------------------------
    class _Node:
        """Lightweight, nonpublic class for storing a singly linked node."""
        __slots__ = "_element", "_next"

        def __init__(self, element, next): #initialize node's fields
            self._element = element
            self._next = next
    #--------------stack methods---------------------------------------
    def __init__(self):
        """Create an empty stack"""
        self._head = None
        self._size = 0

    def top(self):
        """Return (but do not remove) the element at the top of the stack.
        Raise Empty exception if the stack is empty."""
        if self.is_empty():
            raise Exception("Stack is empty")
        return self._head._element


    def __len__(self)->int:
        return self._size


    def is_empty(self)->bool:
        return len(self._size) == 0


    def push(self, e) -> None:
        self._head = self._Node(e, self._head) #create and link a new node
        self._size += 1


    def pop(self)

对顶级方法的引用是:

def top(self):
    """Return (but do not remove) the element at the top of the stack.
    Raise Empty exception if the stack is empty."""
    if self.is_empty():
        raise Exception("Stack is empty")
    return self._head._element

我想将其注释为:

def top(self)-> _Node._element:

如何以体面的方式完成它?

0 个答案:

没有答案