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读取sqlite数据库文件的方法分析
Aug 07 Python
Python实现的摇骰子猜大小功能小游戏示例
Dec 18 Python
Python下载网络小说实例代码
Feb 03 Python
Python中enumerate()函数编写更Pythonic的循环
Mar 06 Python
Selenium定位元素操作示例
Aug 10 Python
Python3爬楼梯算法示例
Mar 04 Python
python取余运算符知识点详解
Jun 27 Python
基于python实现的百度音乐下载器python pyqt改进版(附代码)
Aug 05 Python
PyQt5+python3+pycharm开发环境配置教程
Mar 24 Python
python3环境搭建过程(利用Anaconda+pycharm)完整版
Aug 19 Python
Lombok插件安装(IDEA)及配置jar包使用详解
Nov 04 Python
Python还能这么玩之用Python做个小游戏的外挂
Jun 04 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
实现树状结构的两种方法
2006/10/09 PHP
分享一个PHP数据流应用的简单例子
2012/06/01 PHP
php中数组首字符过滤功能代码
2012/07/31 PHP
ThinkPHP文件缓存类代码分享
2015/04/22 PHP
php判断表是否存在的方法
2015/06/18 PHP
thinkPHP中volist标签用法示例
2016/12/06 PHP
发现的以前不知道的函数
2006/09/19 Javascript
jquery 最简单易用的表单验证插件
2010/02/27 Javascript
JQuery1.4+ Ajax IE8 内存泄漏问题
2010/10/15 Javascript
Extjs TimeField 显示正常时间格式的代码
2011/06/28 Javascript
Js 时间函数getYear()的使用问题探讨
2013/04/01 Javascript
jQuery实现等比例缩放大图片让大图片自适应页面布局
2013/10/16 Javascript
js获取ajax返回值代码
2014/04/30 Javascript
jquery.mobile 共同布局遇到的问题小结
2015/02/10 Javascript
仿iframe效果Aajx文件上传实例
2016/11/18 Javascript
ES6新特性二:Iterator(遍历器)和for-of循环详解
2017/04/20 Javascript
vue.js学习之UI组件开发教程
2017/07/03 Javascript
SeaJS中use函数用法实例分析
2017/10/10 Javascript
webstrom Debug 调试vue项目的方法步骤
2018/07/17 Javascript
详谈js的变量提升以及使用方法
2018/10/06 Javascript
JS绘图Flot如何实现可选显示曲线图功能
2020/10/16 Javascript
[03:17]DOTA2-DPC中国联赛1月29日Recap集锦
2021/03/11 DOTA
使用Python爬虫库BeautifulSoup遍历文档树并对标签进行操作详解
2020/01/25 Python
Python迭代器Iterable判断方法解析
2020/03/16 Python
Python3通过chmod修改目录或文件权限的方法示例
2020/06/08 Python
解决Python3.8运行tornado项目报NotImplementedError错误
2020/09/02 Python
英国最大的独立家具零售商:Furniture Village
2016/09/06 全球购物
华丽的手绘陶瓷:MacKenzie-Childs
2017/02/04 全球购物
物业客服专员岗位职责
2013/11/30 职场文书
公司道歉信范文
2014/01/09 职场文书
小学英语教学反思案例
2014/02/04 职场文书
《最后的姿势》教学反思
2014/02/27 职场文书
祖国在我心中的演讲稿
2014/05/04 职场文书
行政文员岗位职责
2015/02/04 职场文书
试用期辞职信范文
2015/03/02 职场文书
pytorch 如何把图像数据集进行划分成train,test和val
2021/05/31 Python