下面是一个简单的 Python 堆栈示例程序:

class Stack:
    def __init__(self):
        self.stack = []

    def push(self, item):
        self.stack.append(item)

    def pop(self):
        if not self.is_empty():
            return self.stack.pop()

    def peek(self):
        if not self.is_empty():
            return self.stack[-1]

    def is_empty(self):
        return len(self.stack) == 0

    def size(self):
        return len(self.stack)

# 示例程序
stack = Stack()

stack.push('A')
stack.push('B')
stack.push('C')
stack.push('D')

print(stack.peek()) # 输出 'D'
print(stack.pop()) # 输出 'D'

stack.push('E')

print(stack.peek()) # 输出 'E'
print(stack.pop()) # 输出 'E'

print(stack.size()) # 输出 3

这个示例程序定义了一个堆栈类 Stack,它包含常见的操作方法,包括 push、pop、peek、is_empty 和 size。这个类的实现使用了一个列表来存储堆栈的元素。在示例程序中,我们创建了一个 Stack 对象,并对其进行了一些操作,包括 push、pop、peek、size 等。最后,我们通过调用 peek、pop 和 size 方法来验证堆栈的行为。

Python 堆栈实现示例 - 详解代码及应用

原文地址: https://www.cveoy.top/t/topic/lrhp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录