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 随机生成中文验证码的实例代码
Mar 20 Python
推荐11个实用Python库
Jan 23 Python
Python面向对象编程中的类和对象学习教程
Mar 30 Python
Python中flatten( )函数及函数用法详解
Nov 02 Python
django admin后台添加导出excel功能示例代码
May 15 Python
详解Python self 参数
Aug 30 Python
使用遗传算法求二元函数的最小值
Feb 11 Python
QML用PathView实现轮播图
Jun 03 Python
Python 实现键盘鼠标按键模拟
Nov 18 Python
Python Spyder 调出缩进对齐线的操作
Feb 26 Python
Python实战之OpenCV实现猫脸检测
Jun 26 Python
python套接字socket通信
Apr 01 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实现从ftp服务器上下载文件树到本地电脑的程序
2009/02/10 PHP
thinkPHP中钩子的使用方法实例分析
2017/11/16 PHP
javascript椭圆旋转相册实现代码
2012/01/16 Javascript
使用apply方法处理数组的三个技巧[译]
2012/09/20 Javascript
jquery 获取表单元素里面的值示例代码
2013/07/28 Javascript
javascript页面上使用动态时间具体实现
2014/03/18 Javascript
JQuery对表格进行操作的常用技巧总结
2014/04/23 Javascript
JavaScript实现的MD5算法完整实例
2016/02/02 Javascript
BootStrap表单验证 FormValidation 调整反馈图标位置的实例代码
2017/05/17 Javascript
nodejs搭建本地服务器轻松解决跨域问题
2018/03/21 NodeJs
解决vue router组件状态刷新消失的问题
2018/08/01 Javascript
详解TypeScript+Vue 插件 vue-class-component的使用总结
2019/02/18 Javascript
java和js实现的洗牌小程序
2019/09/30 Javascript
原生js实现随机点名功能
2019/11/05 Javascript
[05:01]3.19DOTA2发布会 我们都是刀塔人
2014/03/25 DOTA
Python实现批量将word转html并将html内容发布至网站的方法
2015/07/14 Python
Python2.7简单连接与操作MySQL的方法
2016/04/27 Python
Python文件读写保存操作的示例代码
2018/09/14 Python
python: 判断tuple、list、dict是否为空的方法
2018/10/22 Python
python之pyqt5通过按钮改变Label的背景颜色方法
2019/06/13 Python
使用django的ORM框架按月统计近一年内的数据方法
2019/07/18 Python
Python生态圈图像格式转换问题(推荐)
2019/12/02 Python
python实现KNN近邻算法
2020/12/30 Python
浅析HTML5 meta viewport参数
2020/10/28 HTML / CSS
Ticketmaster德国票务网站:购买音乐会和体育等门票
2016/11/14 全球购物
加拿大女包品牌:Matt & Nat
2017/05/12 全球购物
英国领先的体验日提供商:Buyagift
2019/04/19 全球购物
Linux常见面试题
2013/03/18 面试题
鲜果饮品店创业计划书
2014/01/21 职场文书
小加工厂管理制度
2014/01/21 职场文书
解除劳动合同协议书范本
2014/04/14 职场文书
滞留工资返还协议书
2014/10/19 职场文书
2015小学五年级班主任工作总结
2015/05/21 职场文书
婚宴新郎致辞
2015/07/28 职场文书
php字符串倒叙
2021/04/01 PHP
Vue3.0中Ref与Reactive的区别示例详析
2021/07/07 Vue.js