首页 > 代码库 > 数据结构 栈(顺序表和链表实现) 回顾练习
数据结构 栈(顺序表和链表实现) 回顾练习
1 #!/usr/bin/env python3 2 3 class StackUnderflow(ValueError): 4 pass 5 6 class Node(object): 7 def __init__(self, elem, next_=None): 8 self.elem = elem 9 self.next = next_ 10 11 class LStack(object): 12 def __init__(self): 13 self._elems = [] 14 15 def is_empty(self): 16 return self._elems == [] 17 18 def push(self, elem): 19 self._elems.append(elem) 20 21 def pop(self): 22 if self.is_empty(): 23 raise StackUnderflow 24 return self._elems.pop() 25 26 def top(self): 27 if self.is_empty(): 28 raise StackUnderflow 29 return self._elems[-1] 30 31 class SStack(object): 32 def __init__(self): 33 self._top = None 34 35 def is_empty(self): 36 return self._top == None 37 38 def push(self, elem): 39 self._top = Node(elem, self._top) 40 41 def pop(self): 42 if self.is_empty(): 43 raise StackUnderflow 44 e = self._top.elem 45 self._top = self._top.next 46 return e 47 48 def top(self): 49 if self.is_empty(): 50 raise StackUnderflow 51 return self._top.elem 52 53 if __name__ == ‘__main__‘: 54 """ 55 ls = LStack() 56 ls.push(3) 57 ls.push(2) 58 print(ls.top()) 59 print(ls.pop()) 60 print(ls.pop()) 61 """ 62 #----------------------------------- 63 ss = SStack() 64 ss.push(3) 65 ss.push(2) 66 print(ss.top()) 67 print(ss.pop()) 68 print(ss.pop())
数据结构 栈(顺序表和链表实现) 回顾练习
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。