python实现数据结构-栈

注:本文档主要是学习《Python核心编程(第二版)》时的练习题。

栈是一种"后进先出"的数据结构(LIFO),是一种操作受限的线性结构,数据只能从栈顶进入和栈顶出去。示意图如下:

 

 代码实现方式如下:

 1 #!/usr/bin/env python
 2 
 3 stack = []
 4 
 5 def pushstack():
 6     stack.append(raw_input('Enter new string: '))
 7 
 8 def popstack():
 9     if len(stack) == 0:
10         print 'Cannot pop from empty stack!'
11     else:
12         print 'Removed [', stack.pop(), ']'
13 
14 def viewstack():
15     print stack
16 
17 CMDs = {'u':pushstack, 'o':popstack, 'v':viewstack}
18 
19 def showmenu():
20     pr = """
21 p(U)sh
22 P(O)p
23 (V)iew
24 (Q)uit
25 Enter choice:"""
26 
27     while True:
28         try:
29             choice = raw_input(pr).strip()[0].lower()
30         except(EOFError, keyboardInterrupt, IndexError):
31             choice = 'q'
32 
33         print '\nYou picked: [%s]' % choice
34         if choice not in 'uovq':
35             print 'Invalid option, try again'
36             continue
37 
38         if choice == 'q':
39             break
40         
41         CMDs[choice]()
42 
43 
44 if __name__ == '__main__':
45     showmenu()

测试现象:

 1 [root@localhost python]# python stack.py 
 2 
 3 p(U)sh
 4 P(O)p
 5 (V)iew
 6 (Q)uit
 7 Enter choice:u
 8 
 9 You picked: [u]
10 Enter new string: abc
11 
12 p(U)sh
13 P(O)p
14 (V)iew
15 (Q)uit
16 Enter choice:u
17 
18 You picked: [u]
19 Enter new string: cde
20 
21 p(U)sh
22 P(O)p
23 (V)iew
24 (Q)uit
25 Enter choice:u
26 
27 You picked: [u]
28 Enter new string: 123
29 
30 p(U)sh
31 P(O)p
32 (V)iew
33 (Q)uit
34 Enter choice:v
35 
36 You picked: [v]
37 ['abc', 'cde', '123']
38 
39 p(U)sh
40 P(O)p
41 (V)iew
42 (Q)uit
43 Enter choice:o
44 
45 You picked: [o]
46 Removed [ 123 ]
47 
48 p(U)sh
49 P(O)p
50 (V)iew
51 (Q)uit
52 Enter choice:o
53 
54 You picked: [o]
55 Removed [ cde ]
56 
57 p(U)sh
58 P(O)p
59 (V)iew
60 (Q)uit
61 Enter choice:v
62 
63 You picked: [v]
64 ['abc']

 

posted @ 2019-12-03 14:04  zhengcixi  阅读(275)  评论(0编辑  收藏  举报
回到顶部