python面向对象练习:构建python的栈结构

需求:

  1.      用列表作为栈的存储容器,实现栈的压栈和出栈操作。

  2.      栈可以表示自己的大小和当前存储了多少元素。

  3.      判断栈是否空栈,判断栈是否满栈。

  4.      显示栈有多少个元素,还有多少个存储空间。

  5.      将栈制为空栈。

  6. 分析:

  7. 需要创建栈(stack)类
  8. 属性:一个空列表(list)

          栈的最大长度(max_count)

    方法:进栈(push) 出栈(pop)

          判空(isEmpty)    判满(isFull)

          元素个数(count)    剩余空间(leftspace)

          清空栈(clean)

  9. class Stack():
        """栈数据结构,
        原理:先进后出
        属性:列表,最大存储空间
        方法:出栈,进栈,判空,判满,元素个数,清空栈,剩余空间"""
    
        def __init__(self, max_count):
            self.list = []
            self.max_count = max_count
    
        # 进栈
        def push(self, element):
            if self.isFull() is False:
                self.list.append(element)
            else:
                print("栈已经满了")
    
        # 出栈
        def pop(self):
            if self.isEmpty() is False:
                return self.list.pop()
            else:
                print("扎牛精控了")
        # 通过列表长度判断栈是否为空
    
        def isEmpty(self):
            if len(self.list) == 0:
                return True
            else:
                return False
        # 通过列表长度判断栈是否已满
    
        def isFull(self):
            if len(self.list) == self.max_count:
                return True
            else:
                return False
        # 栈中元素个数
    
        def count(self):
            return len(self.list)
        # 剩余空间
    
        def leftspace(self):
            return self.max_count - len(self.list)
    
        # 将栈置为空栈
        def clean(self):
            self.list.clear()
    
    stact01 = Stack(10)
    stact01.push("xiaoming")
    stact01.push("sanming")
    print("进栈二个元素后:")
    print("栈中元素个数为:"+str(stact01.count())+"    剩余空间为:"+str(stact01.leftspace()))
    stact01.pop()
    print("出栈一个元素后:")
    print("栈中元素个数为:"+str(stact01.count())+"    剩余空间为:"+str(stact01.leftspace()))
    stact01.clean()
    print("清空栈后:")
    print("栈中元素个数为:"+str(stact01.count())+"    剩余空间为:"+str(stact01.leftspace()))
    

    结果:

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

粉尘伴终生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值