一、栈的特点
保证元素后进先出关系的容器
二、顺序栈
栈的空间是固定的,顺序对里面的元素进行入栈,出栈
class Stack:
def __init__(self, maxsize):
self.max = maxsize # 栈的最大容量
self.elem = [None for i in self.max] # 顺序栈
self.top = 0 # 栈顶指针
self.base = 0 # 栈底指针
# 压栈
def push(self, elem):
if self.top - self.base == self.max:
print("栈已满")
return False
self.elem[self.top] = elem
self.top += 1
# 弹栈
def pop(self):
if self.top == 0:
print("栈为空")
return False
self.elem[self.top] = None
self.top -= 1
# 取栈顶元素
def get_top(self):
return self.elem[self.top - 1]
三、链栈
可以动态实现栈空间的增减
# 链栈节点类
class StackNode:
def __init__(self, elem=None):
self.elem = elem # 数据
self.next = None # 指针
# 链栈类
class LinkStack:
def __init__(self):
self.link_top = None # 链栈的指针,指向栈顶元素
# 压栈
def push(self, elem):
s = StackNode(elem)
s.next = self.link_top
self.link_top = s
# 弹栈
def pop(self):
node = self.link_top.elem
self.link_top = self.link_top.next
return node
# 获取栈顶元素
def get_top_elem(self):
return self.link_top.elem
# 获取链栈长度
def get_len(self):
top = self.link_top
count = 0
while top:
count += 1
top = top.next
return count