Python实现栈的方法详解【基于数组和单链表两种方法】
作者:guyt_ 发布时间:2022-06-05 19:03:47
标签:Python,栈,数组,单链表
本文实例讲述了Python实现栈的方法。分享给大家供大家参考,具体如下:
前言
使用Python 实现栈。
两种实现方式:
基于数组 - 数组同时基于链表实现
基于单链表 - 单链表的节点时一个实例化的node 对象
完整代码可见GitHub:
https://github.com/GYT0313/Python-DataStructure/tree/master/5-stack
目录结构:
注:一个完整的代码并不是使用一个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. 基于数组
运行示例:
代码:
栈实现: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. 基于链表
运行示例:
代码:
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程序设计有所帮助。
来源:https://blog.csdn.net/qq_38038143/article/details/89361096


猜你喜欢
- 一、INSERT和REPLACEINSERT和REPLACE语句的功能都是向表中插入新的数据。这两条语句的语法类似。它们的主要区别是如何处理
- 本文实例讲述了Python读取文件内容的三种常用方式。分享给大家供大家参考,具体如下:本次实验的文件是一个60M的文件,共计392660行内
- 一、添加user到group第一种:user.groups.add(1) # add by id第二种:from django.contri
- 应用 Scrapy框架 ,配置动态IP处理反爬。# settings 配置中间件DOWNLOADER_MIDDLEWARES = { &nb
- 最近看Python看得都不用tab键了,哈哈。今天看了一个经典问题--八皇后问题,说实话,以前学C、C++的时候有这个问题,但是当时不爱学,
- 一、xajax与其它ajax框架的比较 xajax功能很简单,但很灵活!~它不象其它一些大的框架,功能确实强大,但执行速度不敢恭维。。功能虽
- 环境准备Python3.5以上Appium Server服务器Android SDK,需要用到adb服务需要依赖Appium-Python-
- 本文实例讲述了Python面向对象之静态属性、类方法与静态方法。分享给大家供大家参考,具体如下:1. 静态属性:在函数前加@property
- 1、Caused by: com.MySQL.jdbc.exceptions.jdbc4.CommunicationsException:T
- 如果 replaceText 为函数,对于每一个匹配的子字符串,调用该函数时带有下面的 m+3 个参数,此处 m 是在 rgExp 中捕获的
- 1、TCP连接的建立方法客户端在建立一个TCP连接时一般需要两步,而服务器的这个过程需要四步,具体见下面的比较。步骤TCP客户端TCP服务器
- 发现一个很简单的配置方法,一直想写的没写上,今天抽空就把它给补充完整好了。本文的配置方法Windows,Mac和Linux系统均适合。一.安
- 一,十进制(decimal system)转换函数说明 1,十进制转二进制 decbin() 函数,如下实例 echo decbin(12)
- 深入认识Python内建类型——dict注:本篇是根据教程学习记录的笔记,部分内容与教程是相同的,因
- 可视化图表,有相当多种,但常见的也就下面几种,其他比较复杂一点,大都也是基于如下几种进行组合,变换出来的。对于初学者来说,很容易被这官网上众
- 计算两个信号的交叉谱密度结果展示:完整代码:import numpy as npimport matplotlib.pyplot
- 视频对象提取与其说是视频对象提取,不如说是视频颜色提取,因为其本质还是使用了OpenCV的HSV颜色物体检测。下面话不多说了,来一起看看详细
- 1、如何放弃正在输入的命令。 在输入一条比较长的命令时,出现打字错误是在所难免的。在这种情况下,放弃正在输入的命令重头再来往往会是更好的选择
- Python编写一个简易银行账户系统,供大家参考,具体内容如下文章中主要涉及的方法是Python中的open(filename, ‘r
- PyMysql使用详解在编写小脚本时,PyMysql是快速连接并操作数据库的一个不错选择。安装pip3 install PyMysql# 可