堆棧是一個后進先出(LIFO)的數據結構. 堆棧這個數據結構可以用于處理大部分具有后進先出的特性的程序流 .
在堆棧中, push 和 pop 是常用術語:
- push: 意思是把一個對象入棧.
- pop: 意思是把一個對象出棧.
下面是一個由 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
47
48
49
50
51
52
53
54
55
|
stack = [] # 初始化一個列表數據類型對象, 作為一個棧 def pushit(): # 定義一個入棧方法 stack.append( raw_input ( 'Enter New String: ' ).strip()) # 提示輸入一個入棧的 String 對象, 調用 Str.strip() 保證輸入的 String 值不包含多余的空格 def popit(): # 定義一個出棧方法 if len (stack) = = 0 : print "Cannot pop from an empty stack!" else : print 'Remove [' , `stack.pop()`, ']' # 使用反單引號(` `)來代替 repr(), 把 String 的值用引號擴起來, 而不僅顯示 String 的值 def viewstack(): # 定義一個顯示堆棧中的內容的方法 print stack CMDs = { 'u' :pushit, 'o' :popit, 'v' :viewstack} # 定義一個 Dict 類型對象, 將字符映射到相應的 function .可以通過輸入字符來執行相應的操作 def showmenu(): # 定義一個操作菜單提示方法 pr = """ p(U)sh p(O)p (V)iew (Q)uit Enter choice: """ while True : while True : try : choice = raw_input (pr).strip()[ 0 ].lower() # Str.strip() 去除 String 對象前后的多余空格 # Str.lower() 將多有輸入轉化為小寫, 便于后期的統一判斷 # 輸入 ^D(EOF, 產生一個 EOFError 異常) # 輸入 ^C(中斷退出, 產生一個 keyboardInterrupt 異常) except (EOFError, KeyboardInterrupt, IndexError): choice = 'q' print ' You picked: [%s]' % choice if choice not in 'uovq' : print 'Invalid option, try again' else : break if choice = = 'q' : break CMDs[choice]() # 獲取 Dict 中字符對應的 functionName, 實現函數調用 if __name__ = = '__main__' : showmenu() |
NOTE: 在堆棧數據結構中, 主要應用了 List 數據類型對象的 容器 和 可變 等特性, 表現在 List.append() 和 List.pop() 這兩個列表類型內建函數的調用.
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/jmilk/article/details/52370692