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实现逆波兰计算表达式实例详解
May 06 Python
利用Python命令行传递实例化对象的方法
Nov 02 Python
Python数据结构与算法之图的广度优先与深度优先搜索算法示例
Dec 14 Python
Python利用splinter实现浏览器自动化操作方法
May 11 Python
Python3中的列表生成式、生成器与迭代器实例详解
Jun 11 Python
使用python将大量数据导出到Excel中的小技巧分享
Jun 14 Python
django 基于中间件实现限制ip频繁访问过程详解
Jul 30 Python
关于python字符串方法分类详解
Aug 20 Python
python+jinja2实现接口数据批量生成工具
Aug 28 Python
python根据时间获取周数代码实例
Sep 30 Python
Python3 把一个列表按指定数目分成多个列表的方式
Dec 25 Python
Python各种扩展名区别点整理
Feb 27 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 IP及IP段进行访问限制的代码
2008/12/17 PHP
PHP实现异步调用方法研究与分享
2011/10/27 PHP
如何使用PHP批量去除文件UTF8 BOM信息
2013/08/05 PHP
PHP类与对象后期静态绑定操作实例详解
2018/12/20 PHP
浅谈php常用的7大框架的优缺点
2020/07/20 PHP
老鱼 浅谈javascript面向对象编程
2010/03/04 Javascript
一款Jquery 分页插件的改造方法(服务器端分页)
2011/07/11 Javascript
浏览器窗口大小变化时使用resize事件对框架不起作用的解决方法
2014/05/11 Javascript
JavaScript动态修改弹出窗口大小的方法
2015/04/06 Javascript
JQuery插件Marquee.js实现无缝滚动效果
2016/04/26 Javascript
angularjs点击图片放大实现上传图片预览
2017/02/24 Javascript
PHP实现本地图片上传和验证功能
2017/02/27 Javascript
10道典型的JavaScript面试题
2017/03/22 Javascript
javascript头像上传代码实例
2019/09/28 Javascript
[38:44]DOTA2上海特级锦标赛A组小组赛#2 Secret VS CDEC第二局
2016/02/25 DOTA
python 字符串格式化代码
2013/03/17 Python
基于python历史天气采集的分析
2019/02/14 Python
Python中最大递归深度值的探讨
2019/03/05 Python
Anaconda之conda常用命令介绍(安装、更新、删除)
2019/10/06 Python
pandas 中对特征进行硬编码和onehot编码的实现
2019/12/20 Python
解决Django部署设置Debug=False时xadmin后台管理系统样式丢失
2020/04/07 Python
python爬虫---requests库的用法详解
2020/09/28 Python
提高python代码运行效率的一些建议
2020/09/29 Python
布局和排版教程 纯css3实现图片三角形排列
2014/10/17 HTML / CSS
定制iPhone和Macbook保护壳:Slick Case
2018/11/21 全球购物
如何开发一个JQuery插件
2016/07/28 面试题
生产现场工艺工程师岗位职责
2013/11/28 职场文书
成功的酒店创业计划书
2013/12/27 职场文书
雪山饭庄的创业计划书范文
2014/01/18 职场文书
学校教师读书活动总结
2014/07/08 职场文书
我的中国梦演讲稿高中篇
2014/08/19 职场文书
经理助理岗位职责
2015/02/02 职场文书
酒店总经理岗位职责
2015/04/01 职场文书
珍惜时间的诗歌赏析
2019/08/23 职场文书
python实现调用摄像头并拍照发邮箱
2021/04/27 Python
python垃圾回收机制原理分析
2022/04/13 Python