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实现发送和获取手机短信验证码
Jan 15 Python
浅谈Python类里的__init__方法函数,Python类的构造函数
Dec 10 Python
Python3实现抓取javascript动态生成的html网页功能示例
Aug 22 Python
django启动uwsgi报错的解决方法
Apr 08 Python
实例详解Matlab 与 Python 的区别
Apr 26 Python
由面试题加深对Django的认识理解
Jul 19 Python
python requests模拟登陆github的实现方法
Dec 26 Python
python matplotlib包图像配色方案分享
Mar 14 Python
Python sql注入 过滤字符串的非法字符实例
Apr 03 Python
python如何停止递归
Sep 09 Python
Python编写单元测试代码实例
Sep 10 Python
python高温预警数据获取实例
Jul 23 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
给apache2.2加上mod_encoding模块後 php5.2.0 处理url出现bug
2007/04/12 PHP
深入PHP异步执行的详解
2013/06/03 PHP
php无法连接mysql数据库的正确解决方法
2016/07/01 PHP
php基于自定义函数记录log日志方法
2017/07/21 PHP
OAuth认证协议中的HMACSHA1加密算法(实例)
2017/10/25 PHP
js下弹出窗口的变通
2007/04/18 Javascript
JavaScript 入门·JavaScript 具有全范围的运算符
2007/10/01 Javascript
理解Javascript_01_理解内存分配原理分析
2010/10/11 Javascript
JavaScript内核之基本概念
2011/10/21 Javascript
关于递归运算的顺序测试代码
2011/11/30 Javascript
通过遮罩层实现浮层DIV登录的js代码
2014/02/07 Javascript
js 获取元素下面所有li的两种方法
2014/04/14 Javascript
Javascript 数组排序详解
2014/10/22 Javascript
js 通过cookie实现刷新不变化树形菜单
2014/10/30 Javascript
jQuery 监控键盘一段时间没输入
2016/04/22 Javascript
AngularJs  unit-testing(单元测试)详解
2016/09/02 Javascript
jQuery UI制作选项卡(tabs)
2016/12/13 Javascript
Node.js 中exports 和 module.exports 的区别
2017/03/14 Javascript
基于casperjs和resemble.js实现一个像素对比服务详解
2018/01/10 Javascript
基于Vue插入视频的2种方法小结
2019/04/02 Javascript
原生JS实现列表内容自动向上滚动效果
2019/05/22 Javascript
python列表操作实例
2015/01/14 Python
Python中使用异常处理来判断运行的操作系统平台方法
2015/01/22 Python
python爬虫headers设置后无效的解决方法
2017/10/21 Python
pyqt5 QProgressBar清空进度条的实例
2019/06/21 Python
django ManyToManyField多对多关系的实例详解
2019/08/09 Python
python实现人工蜂群算法
2020/09/18 Python
澳洲健康食品网上商店:Aussie Health Products
2018/06/15 全球购物
网络编程中设计并发服务器,使用多进程与多线程,请问有什么区别?
2016/03/27 面试题
晚会邀请函范文
2014/01/24 职场文书
最新结婚典礼主持词
2014/03/14 职场文书
《第一次抱母亲》教学反思
2014/04/16 职场文书
教师工作表现评语
2014/12/31 职场文书
放弃继承权公证书
2015/01/23 职场文书
springboot 启动如何排除某些bean的注入
2021/08/02 Java/Android