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)
原文地址:https://www.cnblogs.com/cmnz/p/6936613.html