首页 > 代码库 > 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