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脚本将文字转换为图片的实例分享
Aug 29 Python
详解django中自定义标签和过滤器
Jul 03 Python
Python实现登录接口的示例代码
Jul 21 Python
详解Python进程间通信之命名管道
Aug 28 Python
Python使用回溯法子集树模板获取最长公共子序列(LCS)的方法
Sep 08 Python
Python实现的寻找前5个默尼森数算法示例
Mar 25 Python
python生成密码字典的方法
Jul 06 Python
python3利用tcp实现文件夹远程传输
Jul 28 Python
Python搭建代理IP池实现接口设置与整体调度
Oct 27 Python
Python中猜拳游戏与猜筛子游戏的实现方法
Sep 04 Python
python 偷懒技巧——使用 keyboard 录制键盘事件
Sep 21 Python
详解基于Scrapy的IP代理池搭建
Sep 29 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制作静态网站的模板框架(四)
2006/10/09 PHP
PHP3 safe_mode 失效漏洞
2006/10/09 PHP
缓存技术详谈―php
2006/12/14 PHP
一个比较简单的PHP 分页分组类
2009/12/10 PHP
php中++i 与 i++ 的区别
2012/08/08 PHP
开启PHP Static 关键字之旅模式
2015/11/13 PHP
PHP安全之register_globals的on和off的区别
2020/07/23 PHP
jquery remove方法应用详解
2012/11/22 Javascript
JS+CSS实现模仿浏览器网页字符查找功能的方法
2015/02/26 Javascript
基于jQuery实现仿51job城市选择功能实例代码
2016/03/02 Javascript
jquery通过name属性取值的简单实现方法
2016/06/20 Javascript
全面了解JavaScirpt 的垃圾(garbage collection)回收机制
2016/07/11 Javascript
jQuery ajaxForm()的应用
2016/10/14 Javascript
基于jQuery使用Ajax动态执行模糊查询功能
2018/07/05 jQuery
vue项目在安卓低版本机显示空白的原因分析(两种)
2018/09/04 Javascript
VUE 自定义组件模板的方法详解
2019/08/30 Javascript
[53:10]Secret vs Pain 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/20 DOTA
[32:56]完美世界DOTA2联赛PWL S3 Rebirth vs CPG 第二场 12.11
2020/12/16 DOTA
Python常用列表数据结构小结
2014/08/06 Python
python实现的简单窗口倒计时界面实例
2015/05/05 Python
在Python中处理列表之reverse()方法的使用教程
2015/05/21 Python
Python使用Redis实现作业调度系统(超简单)
2016/03/22 Python
Python字符串拼接的几种方法整理
2017/08/02 Python
Python标准模块--ContextManager上下文管理器的具体用法
2017/11/27 Python
Python 12306抢火车票脚本 Python京东抢手机脚本
2018/02/06 Python
Django框架基础模板标签与filter使用方法详解
2019/07/23 Python
python word转pdf代码实例
2019/08/16 Python
Python requests获取网页常用方法解析
2020/02/20 Python
一文轻松掌握python语言命名规范规则
2020/06/18 Python
Speedo速比涛法国官方网站:泳衣、泳镜、泳帽、泳裤
2019/07/30 全球购物
EJB的角色和三个对象
2015/12/31 面试题
男方父母婚礼答谢词
2014/01/25 职场文书
房屋继承公证书
2014/04/10 职场文书
公司副总经理岗位职责
2014/10/01 职场文书
网络销售员岗位职责
2015/04/11 职场文书
深入浅出讲解Java8函数式编程
2022/01/18 Java/Android