码迷,mamicode.com
首页 > 编程语言 > 详细

python实现之极简stack和quene

时间:2014-10-19 15:28:20      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   strong   sp   div   on   log   代码   

用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

标签:style   blog   color   strong   sp   div   on   log   代码   

原文地址:http://www.cnblogs.com/tudas/p/stack_quene_with_python_implemention.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!