python实现之极简stack和queue

用python实现一个极简的stack和queue,那是so easy的事情了,简洁易懂,适合小白~

直接上代码吧:

node:

class LinkNode:
def __init__( self, value ):
self.value = value
self.next = None

stack:

class Stack:
def __init__( self ):
self.top = None def peek( self ):
if not self.top:
return None
return self.top.value def is_empty( self ):
return self.top == None def pop( self ):
if not self.top:
return None
old_top = self.top
self.top = self.top.next
return old_top.value def push( self, value ):
node = LinkNode( value )
node.next = self.top
self.top = node

queue:

class Queue:
def __init__( self ):
self.first = None
self.last = None def is_empty( self ):
return self.last == None def dequeue( self ):
if not self.first:
return None
old_first = self.first
self.first = self.first.next
if not self.first:
self.last = None
return old_first.value def enqueue( self, value ):
node = LinkNode( value )
if not self.last:
self.first = node
self.last = node
else:
self.last.next = node
self.last = node

test case:

# '''
# Stack test case
# '''
s = Stack()
s.push( 1 )
s.push( 0 )
s.push( -1 )
s.push( -1 )
s.push( 6 )
print( s.peek() )
s.pop()
print( s.peek() ) s.pop()
s.pop()
s.pop()
print( s.peek() ) s.pop()
print( s.top ) # '''
# Queue test case
# '''
q = Queue()
q.enqueue( 1 )
q.enqueue( 2 )
q.enqueue( 0 )
q.enqueue( -1 )
q.enqueue( 8 )
q.dequeue()
q.dequeue()
q.dequeue()
q.dequeue()
print( q.first.value )
上一篇:Qt install Phonon


下一篇:UICollectionView介绍