首页 > 代码库 > python实现之极简stack和quene
python实现之极简stack和quene
用python实现一个极简的stack和quene,那是简单不过的事情了,简洁易懂,适合小白~
直接上代码吧:
node:
class Node: def __init__( self, val ): self.val = val self.next = None
stack:
class Stack: def __init__( self ): self.top = None def peek( self ): return self.top def pop( self ): if not self.top: return None else: old_top = Node( self.top.val ) self.top = self.top.next return old_top def push( self, val ): node = Node( val ) node.next = self.top self.top = node
quene:
class Quene: def __init__( self ): self.first = None self.last = None def dequene( self ): if not self.first: return None else: node = Node( self.first.val ) self.first = self.first.next return node def enquene( self, val ): if not self.last: node = Node( val ) self.first = node self.last = node else: node = Node( val ) self.last.next = node self.last = node
test case:
‘‘‘test case‘‘‘s = Stack()s.push( 1 )s.push( 0 )s.push( -1 )s.push( -1 )s.push( 6 )print( s.peek().val )s.pop()print( s.peek().val )s.pop()s.pop()s.pop()print( s.peek().val )s.pop()print( s.top )‘‘‘Quene test case‘‘‘q = Quene()q.enquene( 1 )q.enquene( 2 )q.enquene( 0 )q.enquene( -1 )q.enquene( 8 )q.dequene()print( q.first.val )
python实现之极简stack和quene
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。