1.栈的工作原理:先进后出
入栈
出栈
栈顶元素
栈的长度
栈是否为空
stack = []
info = """
栈操作
1.入栈
2.出栈
3.栈顶元素
4.栈的长度
5.栈是否为空
"""
while True:
print(info)
choice = input('请输入选择:')
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('欢迎下次使用')
break
else:
print('请输入正确的选择')
2.队列的工作原理:先进先出
入队
出队
队头
队尾
队列是否为空
显示队列元素
stack = []
while True:
info = """
1.入队
2.出队
3.队头
4.队尾
5.队列是否为空
6.显示队列元素
"""
print(info)
chioce = input('请选择:')
if chioce == '1':
instack = input('请输入入队元素:')
stack.insert(0,instack)
# 因为先进后出,所以每次入栈元素都应该放在索引为1的地方
print('%s入队成功' %(instack))
if chioce == '2':
if len(stack) == 0:
print('队列为空,无法出队')
else:
item = stack.pop()
print('%s出队成功' %(item))
if chioce == '3':
if not stack:
print('队列为空,没有队头元素')
else:
print('队头元素为:%s' %(stack[-1]))
# 队头应为最先出队的元素,即为索引最后的元素
if chioce == '4':
if not stack:
print('队列为空,没有队尾元素')
else:
print('队尾元素为:%s' %(stack[0]))
# 队尾应为最后出队的元素,即为索引的第一个元素
if chioce == '5':
if not stack:
print('队列为空')
else:
print('队列不为空')
if chioce == '6':
if not stack:
print('队列为空,没有元素')
else:
print('队列为:%s' %(stack[:]) )
if chioce == 'q':
break
else:
print('请输入正确的选择')