要实现此类需求,可以在类中添加堆栈相关的方法和属性。例如,我们可以使用List类作为堆栈的基础类型,并在其上实现常见的堆栈操作。 以下是一个示例代码:
class Stack:
def __init__(self):
self._stack = []
def push(self, value):
self._stack.append(value)
def pop(self):
return self._stack.pop()
def is_empty(self):
return not bool(self._stack)
s = Stack()
s.push('a')
s.push('b')
s.push('c')
print(s.pop()) # 输出 'c'
print(s.pop()) # 输出 'b'
print(s.is_empty()) # 输出 False
上述代码中,我们通过在类中添加push()、pop()和is_empty()方法,将类声明为堆栈类。此处使用List类作为堆栈的基础类型,同时也可选择使用其他数据结构,如链表、数组等。通过这些方法,我们可以向堆栈中添加元素、弹出元素并检查堆栈是否为空。
上一篇:芭蕾舞者:神秘的“方法过大”错误