python下构造类实现栈

本文提供了一个简单的栈操作实例代码,包括栈的初始化、元素的压入与弹出、获取栈顶元素、查看栈长度及判断栈是否为空等基本功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实例代码

class Stack():
    def __init__(self, initstack):
        self.initstack = initstack

    def in_stack(self, number):
        # self.number = number
        self.initstack.append(number)
        print('Now,the stack is %s.' % str(self.initstack))

    def out_stack(self):
        print('The pop number is %d.' % self.initstack.pop())
        print('Now,the stack is %s.' % str(self.initstack))

    def top_stack(self):
        print('The top number in stack is %d.' %self.initstack[-1])

    def length_stack(self):
        print('The length of the stack is %d.' % len(self.initstack))

    def isnull_stack(self):
        if len(self.initstack) == 0:
            print('Stack Is Null.')
        else:
            print('Stack Is Not Null.')


P1 = Stack([10, 20])
P1.in_stack(5)
P1.length_stack()
P1.out_stack()
P1.top_stack()
P1.isnull_stack()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值