江西中慧城乡建设开发公司网站,阜新建设网站,怎么用ps做静态网站,苏州做网站设计数据结构链表之栈
栈的概述
定义#xff1a;栈是一种基于先进后出(FILO)的数据结构#xff0c;是一种只能在一段进行插入和删除操作的特殊线性表。引入名词#xff1a;将数据存入栈的动作称为压栈#xff0c;将数据取出栈的动作称为弹栈栈的特点#xff1a;先进入栈的元…数据结构链表之栈
栈的概述
定义栈是一种基于先进后出(FILO)的数据结构是一种只能在一段进行插入和删除操作的特殊线性表。引入名词将数据存入栈的动作称为压栈将数据取出栈的动作称为弹栈栈的特点先进入栈的元素会被压入栈底最后一位元素所处的位置就是栈顶弹栈时最后一个元素最先被读取依次往下取出因此叫做First In Last Out
栈可以用顺序表(python中列表)实现也可以用链表实现这里实现的方式的是使用链表有兴趣的同学可以自己编写代码用列表实现栈
python代码实现
class Node:def __init__(self, item):self.item itemself.next Noneclass Stack:def __init__(self):self.head Noneself.len 0def is_empty(self):return not self.len# def length(self):# return self.lendef push(self, item):Push an element into the stacknode Node(item)node.next self.headself.head nodeself.len 1def pop(self):Pop a value from the stack top# if not self.head:# raise IndexError(pop from empty list)cur self.headif self.head:self.head self.head.nextself.len - 1return cur# Make the Stack iterabledef __iter__(self):self.cur self.head# if not self.cur:# raise StopIteration # The error here will be raised if the condition were reachedreturn selfdef __next__(self):if not self.cur:raise StopIteration # The error here actually wont be raisedtry:temp self.curself.cur self.cur.nextreturn tempexcept AttributeError as e:raise StopIteration主要实现的功能
is_empty()判断栈是否为空length()同len属性可以返回栈的长度push()向栈压入元素pop()从栈顶取出一个元素重写的__iter__()和__next__()用于实现栈的遍历功能
功能验证
if __name__ __main__:stack Stack()print(fIs empty? {stack.is_empty()})print(Push elements into the stack:)stack.push(a)stack.push(b)stack.push(c)stack.push(d)# Iterate the stackfor item in stack:print(item.item, end )print(f\nPop a value from the top stack: {stack.pop().item})print(fThe 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