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


Posted in Python onFebruary 22, 2020

本文实例讲述了Python实现栈的方法。分享给大家供大家参考,具体如下:

前言

使用Python 实现栈。
两种实现方式:

  • 基于数组 - 数组同时基于链表实现
  • 基于单链表 - 单链表的节点时一个实例化的node 对象

完整代码可见GitHub:
https://github.com/GYT0313/Python-DataStructure/tree/master/5-stack

目录结构:
Python实现栈的方法详解【基于数组和单链表两种方法】
注:一个完整的代码并不是使用一个py文件,而使用了多个文件通过继承方式实现。

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. 基于数组

运行示例:
Python实现栈的方法详解【基于数组和单链表两种方法】
代码:
栈实现: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

<variable> = array(<capacity>, <optional fill value>)

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. 基于链表

运行示例:
Python实现栈的方法详解【基于数组和单链表两种方法】
代码:
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自动zip压缩目录的方法
Jun 28 Python
Python字符编码判断方法分析
Jul 01 Python
python select.select模块通信全过程解析
Sep 20 Python
利用Python将文本中的中英文分离方法
Oct 31 Python
详解如何用django实现redirect的几种方法总结
Nov 22 Python
python re库的正则表达式入门学习教程
Mar 08 Python
在Django model中设置多个字段联合唯一约束的实例
Jul 17 Python
python实现最小二乘法线性拟合
Jul 19 Python
python函数的万能参数传参详解
Jul 26 Python
python 叠加等边三角形的绘制的实现
Aug 14 Python
Django配置跨域并开发测试接口
Nov 04 Python
使用pandas实现筛选出指定列值所对应的行
Dec 13 Python
Python栈的实现方法示例【列表、单链表】
Feb 22 #Python
python实现滑雪者小游戏
Feb 22 #Python
python实现拼图小游戏
Feb 22 #Python
Python双链表原理与实现方法详解
Feb 22 #Python
Python单链表原理与实现方法详解
Feb 22 #Python
python函数enumerate,operator和Counter使用技巧实例小结
Feb 22 #Python
python通过文本在一个图中画多条线的实例
Feb 21 #Python
You might like
再次研究下cache_lite
2007/02/14 PHP
php adodb连接带密码access数据库实例,测试成功
2008/05/14 PHP
PHP strtr() 函数使用说明
2008/11/21 PHP
如何用php生成扭曲及旋转的验证码图片
2013/06/07 PHP
解析php中array_merge与array+array的区别
2013/06/21 PHP
PHP 关于访问控制的和运算符优先级介绍
2013/07/08 PHP
php获得用户ip地址的比较不错的方法
2014/02/08 PHP
简单的php新闻发布系统教程
2014/05/09 PHP
php中substr()函数参数说明及用法实例
2014/11/15 PHP
解决Laravel 使用insert插入数据,字段created_at为0000的问题
2019/10/11 PHP
JQuery浮动DIV提示信息并自动隐藏的代码
2010/08/29 Javascript
javascript实现div的拖动并调整大小类似qq空间个性编辑模块
2012/12/12 Javascript
JavaScript根据数据生成百分比图和柱状图的实例代码
2013/07/14 Javascript
javascript教程:关于if简写语句优化的方法
2014/05/17 Javascript
基于JavaScript FileReader上传图片显示本地链接
2016/05/27 Javascript
json格式的javascript对象用法分析
2016/07/04 Javascript
JS实现鼠标滑过显示边框的菜单效果
2016/09/21 Javascript
Javascript刷新页面的实例
2017/09/23 Javascript
Angular实现的table表格排序功能完整示例
2017/12/22 Javascript
Angular ng-animate和ng-cookies用法详解
2018/04/18 Javascript
利用Dectorator分模块存储Vuex状态的实现
2019/02/05 Javascript
浅谈Vue.use到底是什么鬼
2020/01/21 Javascript
[01:08]DOTA2次级职业联赛 - Shield战队宣传片
2014/12/01 DOTA
[54:10]Spirit vs NB Supermajor小组赛 A组败者组决赛 BO3 第一场 6.2
2018/06/03 DOTA
pandas 空的dataframe 插入列名的示例
2018/10/30 Python
Python读取csv文件实例解析
2019/12/30 Python
Python filter过滤器原理及实例应用
2020/08/18 Python
python中的插入排序的简单用法
2021/01/19 Python
阿联酋航空官方网站:Emirates
2017/10/17 全球购物
土木工程实习生自我鉴定
2013/09/19 职场文书
副厂长岗位职责
2014/02/02 职场文书
教师国庆节演讲稿范文2014
2014/09/21 职场文书
失职检讨书大全
2015/01/26 职场文书
工作感想范文
2015/08/07 职场文书
详解Java实践之适配器模式
2021/06/18 Java/Android
MongoDB连接数据库并创建数据等使用方法
2021/11/27 MongoDB