1.模拟栈操作原理
先进后出
?1.初始化(创建一个存储数据的列表)
2.进栈使用列表保存数据
? 3.出栈 使用列表删除数据
? 4.查看栈顶元素 切片获取列表最后一位数据
?5.判断是否为空栈
6.栈的长度
程序
stack=[]
info="""
********栈操作******
1.入栈
2.出栈
3.栈顶元素
4.栈的长度
5.栈是否为空
"""
while True:
print(info)
choice=input("please input your choice:")
if choice==‘1‘:
item=input(‘请输入入栈元素:‘)
stack.append(item)
print(‘%s入栈成功!‘%item)
elif choice==‘2‘:
if not stack:
print(‘栈为空,不能出栈!‘)
else:
item=stack.pop()
print(‘%s出栈成功!‘%item)
elif choice==‘3‘:
if len(stack)==0:
print(‘栈为空!‘)
else:
print(‘栈顶元素为:%s‘%stack[-1])
elif choice==‘4‘:
print(‘栈的长度为%s‘%len(stack))
elif choice==‘5‘:
if len(stack)==0:
print(‘栈为空!‘)
else:
print(‘栈不为空!‘)
elif choice==‘q‘:
print(‘logout‘)
break
else:
print(‘Error:check your input!‘)
输出结果:
********栈操作****** 1.入栈 2.出栈 3.栈顶元素 4.栈的长度 5.栈是否为空 please input your choice:1 请输入入栈元素:2 2入栈成功! ********栈操作****** 1.入栈 2.出栈 3.栈顶元素 4.栈的长度 5.栈是否为空 please input your choice:
原文:https://www.cnblogs.com/Xanyang/p/14628170.html