本文实例讲述了Python实现基本数据结构中栈的操作。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
#! /usr/bin/env python #coding=utf-8 #Python实现基本数据结构---栈操作 class Stack( object ): def __init__( self ,size): self .size = size self .stack = [] self .top = 0 #初始化,top=0时则为空栈 def push( self ,x): if self .stackFull(): #进栈之前检查栈是否已满 raise Exception( "overflow !" ) else : self .stack.append(x) self .top = self .top + 1 #push进去的第一个元素下标为1 def pop( self ): if self .stackEmpty(): raise Exception( "underflow !" ) else : self .top = self .top - 1 return self .stack.pop() #利用Python内建函数pop()实现弹出 def stackEmpty( self ): if self .top = = 0 : #判断栈空 return True else : return False def stackFull( self ): if self .top = = self .size: #判断栈满!!! return True else : return False if __name__ = = '__main__' : print "服务器之家测试结果:" s = Stack( 10 ) for i in range ( 3 ): s.push(i) print s.stack print s.pop() print s.stack print s.pop() print s.pop() print s.stack print s.stackEmpty() print s.stackFull() for i in range ( 10 ): s.push(i) print s.stackFull() |
运行结果:
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://blog.csdn.net/will130/article/details/45269943