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,