python中的栈结构_对Python列表进行封装和二次开发实现自定义栈结构
設(shè)計自定義棧類,模擬入棧、出棧、判斷棧是否為空、是否已滿以及改變棧大小等操作。
class Stack:
#構(gòu)造方法
def __init__(self, maxlen = 10):
self._content = []
self._size = maxlen
self._current = 0
#析構(gòu)方法,釋放列表控件
def __del__(self):
del self._content
#清空棧中的元素
def clear(self):
self._content = []
self._current = 0
#測試棧是否為空
def isEmpty(self):
return not self._content
#修改棧的大小
def setSize(self, size):
#不允許新大小小于已有元素數(shù)量
if size < self._current:
print('new size must >=' + str(self._current))
return
self._size = size
#測試棧是否已滿
def isFull(self):
return self._current == self._size
#入棧
def push(self, v):
if self._current < self._size:
#在列表尾部追加元素
self._content.append(v)
#棧中元素個數(shù)加1
self._current = self._current + 1
else:
print('Stack Full!')
#出棧
def pop(self):
if self._content:
#棧中元素個數(shù)減1
self._current = self._current - 1
#彈出并返回列表尾部元素
return self._content.pop()
else:
print('Stack is empty!')
def __str__(self):
return 'Stack(' + str(self._content) +', maxlen=' + str(self._size) + ')'
#復(fù)用__str__方法的代碼
__repr__ = __str__
將代碼保存為myStack.py文件,下面的代碼演示了自定義棧結(jié)構(gòu)的用法。
>>> from myStack import Stack #導(dǎo)入自定義棧
>>> s = Stack() #創(chuàng)建棧對象
>>> s.push(5) #元素入棧
>>> s.push(8)
>>> s.push('a')
>>> s.pop() #元素出棧
'a'
>>> s.push('b')
>>> s.push('c')
>>> s #查看棧對象
Stack([5, 8, 'b', 'c'], maxlen=10)
>>> s.setSize(8) #修改棧大小
>>> s
Stack([5, 8, 'b', 'c'], maxlen=8)
>>> s.setSize(3)
new size must >=4
>>> s.clear() #清空棧元素
>>> s.isEmpty()
True
>>> s.setSize(2)
>>> s.push(1)
>>> s.push(2)
>>> s.push(3)
Stack Full!
總結(jié)
以上是生活随笔為你收集整理的python中的栈结构_对Python列表进行封装和二次开发实现自定义栈结构的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sqlserver 安装_安装sqlse
- 下一篇: python没有上方工具栏_Python