堆栈:是有操作限制的线性表。只能在表的一端就行增加和删除操作。
(数据结构考虑两个东西,一是数据对象集,二是操作集。)
数据对象集是0个或多个数据的有穷线性表。
操作集:create,push,pop,isEmpty,isFull。
每次push要先判断堆栈是否已满;
每次pop要先判断堆栈是否为空。
python的堆栈对应list,list.append(),list.pop().
练习
用数组存放两个堆栈,要求最大地利用数组空间,使得数组只要有空间入栈操作就可以成功。
def push(main_list,stack1,stack2,top1,top2,x,tag):
# top1是堆栈1的顶部,top2是堆栈2的顶部。
# 堆栈1为空时,top1=-1,堆栈2为空时,top2=100。
# 当top2-top1=1时,说明堆栈满
if top2-top1 == 1:
print(‘full’)
return
if tag == 1:
stack1.append(x)
top1 += 1
elif tag == 2:
stack2.append(x)
top2 += 1
return
def pop(main_list,stack1,stack2,top1,top2,tag):
# tag是用来判断是对哪个堆栈操作
if tag == 1:
# pop时先判断堆栈是否为空
if top1 == -1:
print(‘stack1 is empty’)
return
else:
stack1.pop()
elif tag == 2:
if top2 == 100:
print(‘stack2 is empty’)
return
else:
stack2.pop()
return