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
0
投稿
猜你喜欢
- 运行环境Python 2.7操作实例1.原始文本格式:空格分隔的txt,例如2016-03-22 00:06:24.4463094 中文测试
- 1. 概述到目前为止,程序的API对任何人都可以编辑或删除,没有任何限制。我们希望有一些更高级的行为,进行身份验证和权限分配,以确保:数据始
- 四年前写的一个内容管理系统,应用在公司内部网上,昨天DBA说其中的SQL语句未使用参数化的调用,导致服务器负担加重,资源占用大。并列出了几个
- 英文的文档在这里,详细全面,本文仅为自己的学习笔记,只是试图通过转述加深自己的学习,不详细不全面。由于浏览器之间的差异,所以在JS中监听事件
- 这篇文章主要介绍了python如何获取apk的packagename和activity,文中通过示例代码介绍的非常详细,对大家的学习或者工作
- 在Python中,正则表达式的group和groups方法是非常有用的函数,用于处理匹配结果的分组信息。group方法是re.MatchOb
- Go语言集成开发环境之VS Code安装使用VS Code是微软开源的一款编辑器,插件系统十分的丰富。下面介绍如何用VS Code搭建go语
- 这篇文章主要介绍了如何使用Python多线程测试并发漏洞,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的
- 阅读《YUI学习笔记(1)》《YUI学习笔记(2)》YAHOO.lang.later,YAHOO.lang.trim,YAHOO.lang.
- 代码如下:Function getCurrentUrl() On Error Resume Next Dim strTemp If LCas
- 一、新手常犯的错误在论坛看到很多帖子代码中都有一个共同的基本错误,字段类型错误。程序和数据库是紧紧相连的,数据库字段文本型或时间型的都使用单
- 保留COOKIES一个小时Response.Cookies("MyCookie").Expires= (now
- 本文实例讲述了Python判断一个list中是否包含另一个list全部元素的方法。分享给大家供大家参考,具体如下:你可以用for in循环+
- 编程需求:使用python+opencv对图像进行处理,把两张图放在一起显示方法:使用numpy模块中的水平堆叠或竖直堆叠完成所有图像的堆叠
- 不同类型的语言支持不同的数据类型,比如 Go 有 int32、int64、uint32、uint64 等不同的数据类型,这些类型占用的字节大
- Request 对象在 scrapy 中 Request 对象代表着请求,即向服务器发送数据,该对象的构造函数原型如下所示:def __in
- 本文实例讲述了python统计字符串中指定字符出现次数的方法。分享给大家供大家参考。具体如下:python统计字符串中指定字符出现的次数,例
- Crawler全名是DomCrawler,是Symfony框架的组件。令人发指的是DomCrawler的没有中文文档,Symfony也没有翻
- 最近看了下go发送smtp邮件,于是总结一下简单示例 先上一个最简单的代码 (网上搂的代码改了改)package mainimport (
- 可以,具体方法如下::<% set fs=createobject("scripting.