# 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]