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正则表达式操作指南(re使用)
Sep 06 Python
把MySQL表结构映射为Python中的对象的教程
Apr 07 Python
python中map、any、all函数用法分析
Apr 21 Python
详细介绍Python的鸭子类型
Sep 12 Python
python 字符串转列表 list 出现\ufeff的解决方法
Jun 22 Python
使用python3+xlrd解析Excel的实例
May 04 Python
Python3实现转换Image图片格式
Jun 21 Python
Window 64位下python3.6.2环境搭建图文教程
Sep 19 Python
通过pykafka接收Kafka消息队列的方法
Dec 27 Python
linux安装python修改默认python版本方法
Mar 31 Python
python使用requests模块实现爬取电影天堂最新电影信息
Apr 03 Python
python将字符串转变成dict格式的实现
Nov 18 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
php框架Phpbean说明
2008/01/10 PHP
PHP zip扩展Linux下安装过程分享
2014/05/05 PHP
让CodeIgniter数据库缓存自动过期的处理的方法
2014/06/12 PHP
dedecms中使用php语句指南
2014/11/13 PHP
[原创]图片分页查看
2006/08/28 Javascript
javascript据option的value值快速设定初始的selected选项
2007/08/13 Javascript
屏蔽F1~F12的快捷键的js函数
2010/05/06 Javascript
基于jquery的仿百度的鼠标移入图片抖动效果
2010/09/17 Javascript
JQuery操作表格(隔行着色,高亮显示,筛选数据)
2012/02/23 Javascript
结合JQ1.9通过js正则判断各种浏览器版本的方法
2013/12/30 Javascript
jQuery判断指定id的对象是否存在的方法
2015/05/22 Javascript
轻松实现javascript数据双向绑定
2015/11/11 Javascript
AngularJS 路由详解和简单实例
2016/07/28 Javascript
javascript鼠标滑过显示二级菜单特效
2020/11/18 Javascript
Bootstrap对话框使用实例讲解
2016/09/24 Javascript
JavaScript给每一个li节点绑定点击事件的实现方法
2016/12/01 Javascript
VUE中使用Vue-resource完成交互
2017/07/21 Javascript
JS实现json对象数组按对象属性排序操作示例
2018/05/18 Javascript
openlayers4实现点动态扩散
2020/08/17 Javascript
让Vue响应Map或Set的变化操作
2020/11/11 Javascript
[30:00]完美世界DOTA2联赛PWL S2 Rebirth vs LBZS 第二场 11.28
2020/12/01 DOTA
python将多个文本文件合并为一个文本的代码(便于搜索)
2011/03/13 Python
Python中matplotlib中文乱码解决办法
2017/05/12 Python
基于python中theano库的线性回归
2018/08/31 Python
windows下python虚拟环境virtualenv安装和使用详解
2019/07/16 Python
Python 3.6打包成EXE可执行程序的实现
2019/10/18 Python
使用sklearn对多分类的每个类别进行指标评价操作
2020/06/11 Python
python实现sm2和sm4国密(国家商用密码)算法的示例
2020/09/26 Python
微软美国官方网站:Microsoft美国
2018/05/10 全球购物
英国在线照明超市:Castlegate Lights
2019/10/30 全球购物
管理学专业个人求职信范文
2013/09/21 职场文书
竞选体育委员演讲稿
2014/04/26 职场文书
汽车广告策划方案
2014/05/31 职场文书
oracle覆盖导入dmp文件的2种方法
2021/05/21 Oracle
四十九个javascript小知识实用技巧
2021/11/20 Javascript
JS轻量级函数式编程实现XDM二
2022/06/16 Javascript