栈是一种“后进先出”或“先进后出”的数据结构,Python列表本身就可以实现栈结构的基本操作。

下面的代码是使用裂变模拟栈结构的用法,实现了入栈,出栈,判断栈是否为空,是否已满以及改变栈大小等操作。

class Stack:
    def __init__(self,size=10):     
        self._content=[]           #使用列表存放栈的元素
        self._size=size             #初始化栈大小
        self._current=0             #栈中元素个数初始化为0

    def empty(self):
        self._content=[]
        self._current=0

    def isEmpty(self):
        if not self._content:
            return True
        else:
            return False

    def setSize(self,size):     #如果缩小栈空间,则删除指定大小之后的已有元素
        if size<self._current:
            for i in range(size,self._current)[::-1]:
                del self._content[i]
            self._current=size
        self._size=size

    def isFull(self):
        if self._current==self._size:
            return True
        else:
            return False

    def push(self,v):
        if len(self._content)<self._size:
            self._content.append(v)
            self._current=self._current+1          #栈中的元素个数加1
        else:
            print('Stack Full!')

    def pop(self):
        if self._current:
            self.current=self._current-1             #栈中的个数减1
            return self._content.pop()
        else:
            print('Stack is empty!')

    def show(self):
        print(self._content)

    def showRemainderSpace(self):
        print('Stack can still PUSH=', self._size-self._current,'elements.')

if __name__=='__main__':
    print('Please use me as a module.')

将代码保存为Stack.py文件,下面代码演示了自定义栈结构的用法:

 1 ======= RESTART: C:/Users/Administrator/Desktop/时间宝/python/Stack.py =======
 2 Please use me as a module.
 3 >>> import Stack
 4 >>> s=Stack.Stack()
 5 >>> s.isEmpty()
 6 True
 7 >>> s.isFull()
 8 False
 9 >>> s.push(5)
10 >>> s.push(8)
11 >>> s.push('a')
12 >>> s.pop()
13 'a'
14 >>> s.push('b')
15 >>> s.push('c')
16 >>> s.show()
17 [5, 8, 'b', 'c']
18 >>> s.showRemainderSpace()
19 ('Stack can still PUSH=', 5, 'elements.')
20 >>> s.setSize(3)
21 >>> s.isFull()
22 True
23 >>> s.show()
24 [5, 8, 'b']
25 >>> s.setSize(5)
26 >>> s.push('d')
27 >>> s.push('ddddddddd')
28 >>> s.push(3)
29 Stack Full!
30 >>> s.show()
31 [5, 8, 'b', 'd', 'ddddddddd']
32 >>> 

以上就是这次分享的内容,有什么错误或有什么问题,请指出!