本示例详细解析了Python中栈的实现机制,旨在为开发者提供实用的参考代码与分析思路。
前言
本文将演示如何利用Python构建栈结构。 主要涵盖两种实现路径:
- 基于数组的存储方案 - 底层依赖数组或链表结构
- 基于单链表的存储方案 - 节点采用实例化的Node对象
完整源代码托管于GitHub仓库: https://github.com/GYT0313/Python-DataStructure/tree/master/5-stack
项目目录布局如下:
注意:完整代码并非单一脚本,而是通过多文件继承架构组织实现。
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
= array(, )
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编程实践有所助益。