数据结构链表之栈
栈的概述
- 定义:栈是一种基于先进后出(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
主要实现的功能:
- is_empty()判断栈是否为空
- length()同len属性,可以返回栈的长度
- push()向栈压入元素
- pop()从栈顶取出一个元素
- 重写的__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