当前位置: 首页 > 编程文章 >

Python实现栈的方法详解【基于数组和单链表两种方法】

Python实现栈的方法详解【基于数组和单链表两种方法】

作者:许知时间:2026-10-21 17:34:27浏览:755

本文介绍使用Python语言实现栈数据结构的两种主要方式:基于数组和基于单链表。文章通过模块化设计,利用抽象基类定义通用接口,分别展示了ArrayStack和LinkedStack的具体实现细节。读者可通过GitHub获取完整的多文件继承结构代码,并结合《数据结构(Python语言描述)》参考学习。

本文目录展开

本示例详细解析了Python中栈的实现机制,旨在为开发者提供实用的参考代码与分析思路。

前言

本文将演示如何利用Python构建栈结构。 主要涵盖两种实现路径:

  • 基于数组的存储方案 - 底层依赖数组或链表结构
  • 基于单链表的存储方案 - 节点采用实例化的Node对象

完整源代码托管于GitHub仓库: https://github.com/GYT0313/Python-DataStructure/tree/master/5-stack

项目目录布局如下: 在这里插入图片描述 注意:完整代码并非单一脚本,而是通过多文件继承架构组织实现。

1. 超类接口代码

arraycollection.py


"""
File: abstractcollection.py
Author: Ken Lambert
"""

class AbstractCollection(object):
  """An abstract collection implementation."""

  # Constructor
  def __init__(self, sourceCollection = None):
    """Sets the initial state of self, which includes the
    contents of sourceCollection, if it's present."""
    self._size = 0
    if sourceCollection:
      for item in sourceCollection:
        self.add(item)

  # Accessor methods
  def isEmpty(self):
    """Returns True if len(self) == 0, or False otherwise."""
    return len(self) == 0
  
  def __len__(self):
    """Returns the number of items in self."""
    return self._size

  def __str__(self):
    """Returns the string representation of self."""
    return "[" + ", ".join(map(str, self)) + "]"

  def __add__(self, other):
    """Returns a new bag containing the contents
    of self and other."""
    result = type(self)(self)
    for item in other:
      result.add(item)
    return result

  def __eq__(self, other):
    """Returns True if self equals other,
    or False otherwise."""
    if self is other: return True
    if type(self) != type(other) or \
      len(self) != len(other):
      return False
    otherIter = iter(other)
    for item in self:
      if item != next(otherIter):
        return False
    return True

abstractstack.py


"""
File: abstractstack.py
Author: Ken Lambert
"""

from abstractcollection import AbstractCollection

class AbstractStack(AbstractCollection):
  """An abstract stack implementation."""

  # Constructor
  def __init__(self, sourceCollection = None):
    """Sets the initial state of self, which includes the
    contents of sourceCollection, if it's present."""
    AbstractCollection.__init__(self, sourceCollection)

  # Mutator methods
  def add(self, item):
    """Adds item to self."""
    self.push(item)

2. 基于数组的实现

运行效果展示: 在这里插入图片描述 核心源码: 栈逻辑实现:arraystack.py


"""
File: abstractstack.py
Author: Ken Lambert
"""

from abstractcollection import AbstractCollection

class AbstractStack(AbstractCollection):
  """An abstract stack implementation."""

  # Constructor
  def __init__(self, sourceCollection = None):
    """Sets the initial state of self, which includes the
    contents of sourceCollection, if it's present."""
    AbstractCollection.__init__(self, sourceCollection)

  # Mutator methods
  def add(self, item):
    """Adds item to self."""
    self.push(item)

数组底层支持:arrays.py


"""
File: arrays.py

An Array is a restricted list whose clients can use
only [], len, iter, and str.

To instantiate, use

 = array(, )

The fill value is None by default.
"""

class Array(object):
  """Represents an array."""

  def __init__(self, capacity, fillValue = None):
    """Capacity is the static size of the array.
    fillValue is placed at each position."""
    self._items = list()
    for count in range(capacity):
      self._items.append(fillValue)

  def __len__(self):
    """-> The capacity of the array."""
    return len(self._items)

  def __str__(self):
    """-> The string representation of the array."""
    return str(self._items)

  def __iter__(self):
    """Supports iteration over a view of an array."""
    return iter(self._items)

  def __getitem__(self, index):
    """Subscript operator for access at index."""
    return self._items[index]

  def __setitem__(self, index, newItem):
    """Subscript operator for replacement at index."""
    self._items[index] = newItem

3. 基于链表的实现

运行效果展示: 在这里插入图片描述 核心源码: linkedstack.py


"""
linkedstack.py
"""

from node import Node
from abstractstack import AbstractStack

class LinkedStack(AbstractStack):
  """基于单链表实现栈-链表头部为栈顶"""

  def __init__(self, source_collection=None):
    self._items = None
    AbstractStack.__init__(self, source_collection)

  def __iter__(self):
    """迭代-使用一个列表实现, 列表第一项为单链表的最后一项"""
    def visit_nodes(node):
      if node != None:
        visit_nodes(node.next)
        temp_list.append(node.data)
    temp_list = []
    visit_nodes(self._items)
    return iter(temp_list)

  def peek(self):
    """返回栈顶元素"""
    self._prior_condition()
    return self._items.data

  def clear(self):
    """清空列表"""
    self._size = 0
    self._items = None

  def push(self, item):
    """入栈"""
    self._items = Node(item, self._items)
    self._size += 1

  def pop(self):
    """出栈"""
    self._prior_condition()
    old_item = self._items.data
    self._items = self._items.next
    self._size -= 1
    return old_item

  def _prior_condition(self):
    if self._size == 0:
      raise KeyError("The stack is empty.")

node.py


"""
链表结构的节点类
"""

class Node(object):
  def __init__(self, data, next=None):
    self.data = data
    self.next = next

参考资料:《数据结构(Python语言描述)》

期望上述内容能对您的Python编程实践有所助益。

上一篇
Python实现队列的方法示例小结【数组,链表】

本文介绍Python中队列(FIFO)的两种常见实现方式。通过列表方法可直接利用append和pop(0)完成入队与出队操作;基于链表则需定义头尾节点,分别处理表尾添加和头部删除逻辑。文中提供了完整的类定义代码及运行结果演示,帮助理解数据结构在Python中的具体应用。

下一篇
Python实现数组、链表、队列与栈的核心逻辑

本文介绍在Python中如何从零实现数组、链表、队列和栈。Python原生列表并非严格意义的数组,需通过类封装模拟固定大小数组行为。文章详细解析了单向链表、双向循环链表的节点设计与指针管理,并基于数组或链表构建了环形队列、双向队列及栈结构,展示了进队、出队、压栈、弹栈等核心操作的代码实现。

相关文章

更多
PHP面向对象实现栈数据结构:入栈、出栈与遍历

本文介绍基于PHP面向对象思想实现的栈数据结构,包含top指针、最大存储容量及数组容器。通过具体代码演示了入栈、出栈和遍历栈的核心方法,并展示了运行结果供参考。

2025.07.10 391
Docker容器化部署Python应用详解

本文介绍了使用Docker进行Python应用容器化的具体步骤。内容涵盖简单Python脚本与Django项目的目录结构规划、Dockerfile编写规范、镜像构建命令以及容器运行配置,包括端口映射、卷挂载及权限设置等关键参数解析。

2025.11.10 986
PHP操作Redis String、Hash和List数据结构代码实例

使用 Predis 或 phpredis 扩展,通过连接实例直接调用 set 、 hSet 、 rPush 等方法操作对应数据结构。

2026.06.12 977
Python 函数与变量中单下划线和双下划线的区别详解

Python 通过下划线前缀区分访问权限。单下划线开头的函数或变量表示模块级私有,`from module import *` 不会导入它们,但在类中表示约定俗成的内部使用,仍可被直接访问。双下划线开头会触发名称修饰(Name Mangling),在类中实现真正的私有化,防止子类意外覆盖。前后双下划线则是 Python 保留的特殊方法(Magic Methods),用于运算符重载等语言特性,用户应避免自定义此类名称。

2025.12.07 973
Python机器学习KNN分类算法详解与实战

KNN(K-Nearest-Neighbors)是一种概念简单且效果优秀的分类算法,其核心思想是通过寻找距离测试样本最近的K个训练样本来投票决定类别。本文介绍KNN的欧式距离计算、K-D Tree与Ball-Tree优化机制,并通过身高体重数据演示Python scikit-learn的实现过程,最终达到0.94的准确率,展示其在处理不规则边界问题上的优势。

2026.09.10 964
Python监控Nginx端口和进程状态

本文提供了一段基于Python的Nginx监控代码,利用psutil库获取主机名称、进程ID及监听端口信息。该脚本通过检测nginx进程是否存在及其对应的端口状态,生成包含主机名、IP、PID和端口的JSON数据,适用于自动化运维中的服务健康检查场景。

2026.03.15 959

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。