python数据结构学习附代码(二)栈

(二)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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值