python 单项链表实现栈

# encoding=UTF-8

"""
    单项链表实现栈
"""


class LinkedStack:
    """LIFO Stack implementation using a singly linked list for storage."""

    # nested _Node class
    class _Node:
        """lightweight, nonpublick class for storing a singly linked  node."""
        __slots__ = '_element', '_next'             # streamline memory usage

        def __init__(self, element, next):          # initialize node's fields
            self._element = element                 # reference to user's element
            self._next = next                       #reference to next node

    # stack methods
    def __init__(self):
        """create an empty stack"""
        self._head = None                           # reference to the head node
        self._size = 0                              # number of stack elements

    def __len__(self):
        """return the number of elements in the stack"""
        return self._size

    def is_empty(self):
        """return True if the stack is empty"""
        return self._size == 0

    def push(self, e):
        """add element e to the top of the stack"""
        self._head = self._Node(e, self._head)      # create and link a new node
        self._size += 1

    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                  # top of stack is at head of list

    def pop(self):
        """remove and return the element from the top of the stack (i.e., LIFO)
        raise empty exception if the stack is empty
        """
        if self.is_empty():
            raise Exception('stack is empty')
        answer = self._head._element
        self._head = self._head._next
        self._size -= 1
        return answer

    def __str__(self):
        arr = []
        head = self._head
        while head is not None:       # self._head 记录当前 node 元素对象,元素对象 _element 记录数据,_next 记录下个元素对象
            arr.append(head._element)
            head = head._next
        return str(arr)


if __name__ == '__main__':
    link = LinkedStack()
    link.push(1)
    link.push(2)
    link.push(4)
    print(link.top())
    print(link)
    print(link.pop())
    print(link)

输出

4
[4, 2, 1]
4
[2, 1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值