数据结构 栈(顺序表和链表实现) 回顾练习
Posted 小黄人python
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构 栈(顺序表和链表实现) 回顾练习相关的知识,希望对你有一定的参考价值。
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())
以上是关于数据结构 栈(顺序表和链表实现) 回顾练习的主要内容,如果未能解决你的问题,请参考以下文章