本文實例講述了Python基于list的append和pop方法實現堆棧與隊列功能。分享給大家供大家參考,具體如下:
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
#coding=utf8 ''''' 堆棧: 堆棧是一個后進先出(LIFO)的數據結構。 在棧上"push"元素是個常用術語,意思是把一個對象添加到堆棧中。 刪除一個元素,可以把它"pop"出堆棧。 隊列: 隊列是一種先進先出(FIFO)的數據類型。 新的元素通過"入隊"的方式添加進隊列的末尾, "出對"就是從隊列的頭部刪除。 ''' #創建列表 def creatList(): initList = [] try : while True : #從鍵上輸入元素 inputItem = raw_input (u "Enter item(輸入quit結束輸入):" ) #當輸入字符不是quit,把元素加入列表 #當輸入字符是quit,結束輸入 if inputItem! = "quit" : initList.append(inputItem.strip()) else : break #返回輸入列表 return initList except Exception,e: print "Create List Error:" ,e #刪除列表的第一個元素并返回刪除元素 def popTheFirst( List ): try : #判斷列表中是否存在元素 #如果存在元素,刪除并返回第一個元素 #如果不存在,給出提示信息 if len ( List )> 0 : return List .pop( 0 ) else : print "The list is empty..." except Exception,e: print "pop the first item Error:" ,e #刪除列表的最后元素并返回刪除元素 def popTheLast( List ): try : #判斷列表中是否存在元素 #如果存在元素,刪除并返回最后元素 #如果不存在,給出提示信息 if len ( List )> 0 : #pop函數默認刪除最后一個元素 return List .pop() else : print "The list is empty..." except Exception,e: print "pop the last item Error:" ,e #調用creatList函數創建表 listOne = creatList() #輸出創建表信息 print "The init list :" ,listOne #調用popTheFirst函數刪除并返回第一個元素 theFirst = popTheFirst(listOne) #輸出當前表的第一個元素 print "The first item of list:" ,theFirst #調用popTheFirst函數刪除并返回最后一個元素 theLast = popTheLast(listOne) #輸出當前表的最后一個元素元素 print "The last item of list:" ,theLast ''''' 這里的listOne、theFirst、theLast都是全局變量 如果更改上述語句順序會獲取不到想要的結果。 ''' |
運行結果:
希望本文所述對大家Python程序設計有所幫助。