1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| class Node(): """节点""" def __init__(self, item=None, next=None): self.item = item self.next = next
class Stack(): """栈""" def __init__(self, node=None): self.head = node def push(self, item): """栈顶插入元素""" self.head = None(item, self.head) def pop(self): """弹出栈顶元素""" if self.head: self.head=self.head.next return return "栈为空栈" def peek(self): """返回栈顶元素""" if self.head: return self.head.item return "栈为空栈" def is_empty(self): """判断是否为空栈""" return self.head==None def size(self): """返回元素个数""" num = 0 node = self.head if node==None: return num num += 1 while node.next!=None: node = node.next num += 1 return num
|