写一个Python自定义数据结构栈。栈是一种后进先出(Last-In-First-Out)的数据结构。编写类 Stack,实现入栈、出栈、判断栈是否为空,是否满栈、以及改变栈容量等操作。 Stack 类包括: 私有成员 content,为一个列表,代表栈里的数据; 私有成员 size,要求为整型,代表栈的容量; 私有成员 current,要求为整型,代表栈当前数据的个数; 方法 isempty,判断栈是否为空,返回 True/False; 方法 empty,置空栈; 方法 setSize,输入参数为新的栈的容量。注意新的栈容量可能小于原有的栈容量,统一将后进的元素删除; 方法 isFull,判断栈是否为满,返回 True/False; 方法 push,入栈,输入参数为新的元素; 方法 pop,出栈; 方法 show,打印当前栈的数据。
时间: 2023-03-07 19:44:35 浏览: 176
答:class Stack:
# 初始化
def __init__(self, size):
self.content = [] # 创建一个空列表,用于储存栈内元素
self.size = size # 栈的容量
self.current = 0 # 栈当前数据的个数
# 判断栈是否为空
def isempty(self):
if self.current == 0:
return True
else:
return False
# 置空栈
def empty(self):
self.content = []
self.current = 0
# 设置新的栈容量
def setSize(self, size):
self.size = size
if self.size < self.current:
self.content = self.content[:self.size]
self.current = self.size
# 判断栈是否为满
def isFull(self):
if self.current == self.size:
return True
else:
return False
# 入栈
def push(self, data):
if self.current < self.size:
self.content.append(data)
self.current += 1
else:
print("Stack is full!")
# 出栈
def pop(self):
if self.current > 0:
self.current -= 1
return self.content.pop()
else:
print("Stack is empty!")
# 打印当前栈的数据
def show(self):
print(self.content)
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)