Python数据结构:栈

#coding=gbk
#栈的常用操作
# Stack()    建立一个空的栈对象
# push()     把一个元素添加到栈的最顶层
# pop()      删除栈最顶层的元素,并返回这个元素
# peek()     返回最顶层的元素,并不删除它
# isEmpty()  判断栈是否为空
# size()     返回栈中元素的个数

#使用Python中的列表进行对栈的实现
class Stack():
    '''对栈进行模拟'''
    def __init__(self):
        self.values = []
    def push(self, value):
        self.values.append(value)
    def pop(self):
        return self.values.pop()
    def peek(self):
        if not self.isEmpty():
            return self.values[len(self.values)-1]
    def isEmpty(self):
        return len(self.values) == 0
    def size(self):
        return len(self.values)
    def print_all(self):
        print(self.values)
s= Stack()
print(s.isEmpty())      #True 代表栈为空 
s.push(12)
s.push(13)
print(s.isEmpty())      #False
print(s.peek())         #13
print(s.size())     #2
print(s.pop())      #13
print(s.peek()) #12
s.push('hello')
s.push('this')
s.push('world')
s.print_all()           #[12, 'hello', 'this', 'world']
print(s.size())



猜你喜欢

转载自blog.csdn.net/qq_40587575/article/details/80835623