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中的内存泄漏
Apr 23 Python
Python 专题三 字符串的基础知识
Mar 19 Python
用python实现的线程池实例代码
Jan 06 Python
对命令行模式与python交互模式介绍
May 12 Python
Python实现的读取/更改/写入xml文件操作示例
Aug 30 Python
Pandas删除数据的几种情况(小结)
Jun 21 Python
Python 占位符的使用方法详解
Jul 10 Python
python机器学习包mlxtend的安装和配置详解
Aug 21 Python
python用requests实现http请求代码实例
Oct 31 Python
python等差数列求和公式前 100 项的和实例
Feb 25 Python
Python3-异步进程回调函数(callback())介绍
May 02 Python
Python sqlalchemy时间戳及密码管理实现代码详解
Aug 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中heredoc的使用方法
2013/06/17 PHP
php增删改查示例自己写的demo
2013/09/04 PHP
在win系统安装配置 Memcached for PHP 5.3 图文教程
2015/03/03 PHP
使用图灵api创建微信聊天机器人
2015/07/23 PHP
PHP实现使用DOM将XML数据存入数组的方法示例
2017/09/27 PHP
php使用lua+redis实现限流,计数器模式,令牌桶模式
2019/04/04 PHP
javascript 装载iframe子页面,自适应高度
2009/03/20 Javascript
JavaScript中this的使用详解
2013/11/08 Javascript
JavaScript定义变量和变量优先级问题探讨
2014/10/11 Javascript
js实现文字滚动效果
2016/03/03 Javascript
浅谈angularJS中的事件
2016/07/12 Javascript
jQuery组件easyui基本布局实现代码
2016/08/25 Javascript
微信小程序中多个页面传参通信的学习与实践
2017/05/05 Javascript
JS设置手机验证码60s等待实现代码
2017/06/14 Javascript
JavaScript设计模式之代理模式实例分析
2019/01/16 Javascript
C#程序员入门学习微信小程序的笔记
2019/03/05 Javascript
Vue实现简单的拖拽效果
2020/08/25 Javascript
[52:37]完美世界DOTA2联赛循环赛 Forest vs DM BO2第一场 10.29
2020/10/29 DOTA
Python采用socket模拟TCP通讯的实现方法
2014/11/19 Python
几个提升Python运行效率的方法之间的对比
2015/04/03 Python
完美解决Python2操作中文名文件乱码的问题
2017/01/04 Python
Python 3.6 读取并操作文件内容的实例
2018/04/23 Python
Python编写通讯录通过数据库存储实现模糊查询功能
2019/07/18 Python
Python+appium框架原生代码实现App自动化测试详解
2020/03/06 Python
python多线程semaphore实现线程数控制的示例
2020/08/10 Python
详解CSS3中@media的实际使用
2015/08/04 HTML / CSS
HTML5 语音搜索只需一句代码
2013/01/03 HTML / CSS
意大利在线大学图书馆:Libreria universitaria
2019/07/16 全球购物
Java面试笔试题大全
2016/11/23 面试题
幼儿园教师个人反思
2014/01/30 职场文书
药学职务聘任书
2014/03/29 职场文书
岗位竞聘书范文
2014/03/31 职场文书
公司领导班子民主生活会对照检查材料
2014/10/02 职场文书
活着观后感
2015/06/03 职场文书
恋恋笔记本观后感
2015/06/16 职场文书
高三数学教学反思
2016/02/18 职场文书