数据结构链表之栈,Python3简单实现——5

数据结构链表之栈

栈的概述

  • 定义:栈是一种基于先进后出(FILO)的数据结构,是一种只能在一段进行插入和删除操作的特殊线性表。
  • 引入名词:将数据存入栈的动作称为压栈,将数据取出栈的动作称为弹栈
  • 栈的特点:先进入栈的元素会被压入栈底,最后一位元素所处的位置就是栈顶,弹栈时最后一个元素最先被读取,依次往下取出,因此叫做First In Last Out
    在这里插入图片描述

栈可以用顺序表(python中列表)实现,也可以用链表实现,这里实现的方式的是使用链表,有兴趣的同学可以自己编写代码用列表实现栈

python代码实现:

class Node:
    def __init__(self, item):
        self.item = item
        self.next = None


class Stack:
    def __init__(self):
        self.head = None
        self.len = 0

    def is_empty(self):
        return not self.len

    # def length(self):
    #     return self.len

    def push(self, item):
        """Push an element into the stack"""
        node = Node(item)
        node.next = self.head
        self.head = node
        self.len += 1

    def pop(self):
        """Pop a value from the stack top"""
        # if not self.head:
        #     raise IndexError("pop from empty list")
        cur = self.head
        if self.head:
            self.head = self.head.next
            self.len -= 1
        return cur

    # Make the Stack iterable
    def __iter__(self):
        self.cur = self.head
        # if not self.cur:
        #     raise StopIteration   # The error here will be raised if the condition were reached
        return self

    def __next__(self):
        if not self.cur:
            raise StopIteration  # The error here actually won't be raised
        try:
            temp = self.cur
            self.cur = self.cur.next
            return temp
        except AttributeError as e:
            raise StopIteration

主要实现的功能:

  1. is_empty()判断栈是否为空
  2. length()同len属性,可以返回栈的长度
  3. push()向栈压入元素
  4. pop()从栈顶取出一个元素
  5. 重写的__iter__()和__next__()用于实现栈的遍历功能

功能验证

if __name__ == "__main__":
    stack = Stack()

    print(f"Is empty? {stack.is_empty()}")

    print("Push elements into the stack:")
    stack.push('a')
    stack.push('b')
    stack.push('c')
    stack.push('d')
    # Iterate the stack
    for item in stack:
        print(item.item, end=' ')

    print(f"\nPop a value from the top stack: {stack.pop().item}")

    print(f"The number(length) of the remanent nodes is: {stack.len}")

输出结果:

Is empty? True
Push elements into the stack:
d c b a 
Pop a value from the top stack: d
The number(length) of the remanent nodes is: 3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值