(二)StackStructure栈结构
栈是线性的集合,其访问操作被严格限制在栈的顶(一端)
栈严格遵从先入后出(或叫后入先出,LIFO)协议
例如, 洗干净的盘子叠起来存放,放在最上面的是最后放上去的盘子
栈的操作包括:
push(item):将item放入栈顶,进栈
pop: 将栈顶的值返回,并将其删除,出栈
peek:返回栈顶的值
python内置的线性结构有数组结构,因此栈可以由数组实现,但数组本身是可以从任何位置访问,且数组的大小初始时固定。
还有一种方法,使用链表构成栈
(一)链表构成的栈
本文使用了抽象集合AbstractStack和AbstrackCollection,以及链表结构类Node,都在文末给出代码
初始化:
"""
File: LinkedStack.py
"""
from AbstractStack import AbstractStack
from node import Node
class linkedStact(AbstractStack):
"""an linked-stack implementation"""
def __init__(self, sourceCollection):
"""initial the state of stack"""
self._items = None
AbstractStack.__init__(self, sourceCollection)
peek操作:
def peek(self):
"""returns the item at top of the stack
Precondition: the stack is not empty"""
if self.isEmpty():
raise KeyError("The stack is empty")
return self._items.data
self.isEmpty在抽象父类AbstractCollection中定义,判定容器是否为空
raise KeyError():抛出一个空值的异常
push操作:
def push(self, item):
""""Insert a item at top of the stack"""
self.size += 1
self._items = Node(item, self._items)
链表的头正好可以作为栈的顶,因此链表添加节点可以直接作为入栈操作
pop操作:
def pop(self):
"""Delete the item at top of the stack and return the item at top of the stack.
Precondition is the stack is not empty"""
if self.isEmpty():
raise KeyError("the stack is empty")
self.size -= 1
item = self._items.data
self._items = self._items.next
return item
先验条件:栈不为空,否则抛出异常
附录:
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
class AbstractStack(AbstractCollection):
"""An abstract stack implementation"""
def __init__(self, sourceCollection=None):
"""initial the state of self"""
AbstractCollection.__init__(self, sourceCollection)
def add(self, item):
self.push(item)
"""
File: node.py
"""
class Node(object):
"""Represents a singly linked node."""
def __init__(self, data, next = None):
self.data = data
self.next = next