04_栈的实现-基于数组 📅 2026/7/31 18:12:17 1、 栈功能的定义方法说明size()返回栈中元素个数is_empty()判断栈是否为空push(item)将新元素压入栈中pop()获取栈顶元素并将栈顶元素弹出栈peek()获取栈顶元素但不弹出栈fromp02_动态数组的实现importmyArrayclassEmptyStackError(Exception):passclassStackArray:def__init__(self):self.__containermyArray()defsize(self):returnself.__container.sizedefis_empty(self):returnself.__container.isEmpty()#假设这里把数组的尾部当作栈顶头部当作栈底defpush(self,item):# 入栈self.__container.append(item)defpop(self):# 出栈ifself.is_empty():# return NoneraiseEmptyStackError(栈为空)returnself.__container.remove(self.__container.size-1)# 最后一个元素下标为 self.__container.size - 1defpeek(self):ifself.is_empty():# return NoneraiseEmptyStackError(栈为空)returnself.__container.get(self.__container.size-1)def__str__(self):returnstr(self.__container)if__name____main__:stackStackArray()print(最初的size:,stack.size())print(是否为空:,stack.is_empty())stack.push(hello)print(stack:,stack)stack.push(world)print(stack:,stack)stack.push(!)print(stack:,stack)try:stack.pop()print(stack:,stack)stack.pop()print(stack:,stack)stack.pop()print(stack:,stack)stack.pop()print(stack:,stack)print(是否为空:,stack.is_empty())stack.pop()print(stack:,stack)print(是否为空:,stack.is_empty())stack.peek(3)exceptEmptyStackErrorase:print(e)