Python_自定義棧


customStack.py

 1 '''棧:是一種運算受限的線性表,其特點在於僅允許在一端進行元素的插入和刪除操作,最后入棧的最先出棧,而最先入棧的元素最后出棧'''
 2 s = []
 3 s.append(3) #在尾部追加元素,模擬入棧操作
 4 s.append(5)
 5 s.append(7)
 6 print(s)
 7 s.pop() #在尾部彈出元素,模擬出棧操作
 8 print('出棧后:',s)
 9 s.pop() #在尾部彈出元素,模擬出棧操作
10 s.pop() #在尾部彈出元素,模擬出棧操作
11 #s.pop() #在尾部彈出元素,模擬出棧操作
12     # Traceback (most recent call last):
13     #   File "/Users/c2apple/PycharmProjects/easyToPython/customStack.py", line 11, in <module>
14     #     s.pop() #在尾部彈出元素,模擬出棧操作
15     # IndexError: pop from empty list
16 
17 #設計自定義棧,模擬入棧,出棧,判斷棧是否為空,是否已滿以及改變棧大小等操作
18 class Stack:
19     def __init__(self,size=10):
20         self._content = [] #使用列表存放棧的元素
21         self._size = size   #初始棧大小
22         self._current = 0   #棧中元素個數初始化為0
23 
24     #析構函數
25     def __del__(self):
26         del self._content
27 
28     def empty(self):
29         self._content = []
30         self._current = 0
31 
32     def isEmpty(self):
33         return not self._content
34 
35     def setSize(self,size):
36         #如果縮小棧空間,則刪除指定大小之后的已有元素
37         if size < self._current:
38             for i in range(size,self._current)[::-1]:
39                 del self._current[i]
40             self._current = size
41         self._size = size
42 
43     def isFull(self):
44         return self._current == self._size
45 
46     def push(self,v):
47         if self._current < self._size:
48             self._content.append(v)
49             self._current = self._current + 1   #棧中元素個數加1
50         else:
51             print('Stack Full!')
52 
53     def pop(self):
54         if self._content:
55             self._current = self._current - 1 #棧中元素個數減1
56             return self._content.pop()
57         else:
58             print('Stack is empty!')
59 
60     def show(self):
61         print(self._content)
62 
63     def showRemainderSpace(self):
64         print('Stack can still PUSh',self._size-self._current,'elements.')

useCustomStack.py

 1 from customStack import Stack   #導入模塊
 2 
 3 s = Stack() #實例化對象
 4 
 5 print('測試棧是否為空:',s.isEmpty())
 6 print('測試棧是否已滿:',s.isFull())
 7 
 8 s.push(5)   #元素入棧
 9 s.push(8)
10 s.push('a')
11 
12 s.pop() #元素出棧
13 
14 s.push('b')
15 s.push('c')
16 s.show()
17 
18 s.showRemainderSpace()  #查看棧的剩余大小
19 print('查看當前current',s._content)
20 s.setSize(4)    #修改棧的大小
21 print('測試棧是否已滿:',s.isFull(),'棧內元素',s._content)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM