题目要求:
栈的工作原理
入栈
出栈
查看栈顶元素
栈的长度
栈是否为空
代码如下:第一种
menu = '''
1. PUSH
2. POP
3. FIND
4. LENGTH
5. ISEMPTY
6. QUIT
'''
Stack = []
while True:
print(menu)
###PUSH
choose = input('Please Input Your choose:')
if choose == '1':
str = input('Str:')
Stack.append(str)
print('PUSH Successful')
###POP
elif choose == '2':
if len(Stack):
###item = Stack.pop()
###print('%s' %item)
i = Stack.index(Stack[-1])
print(Stack.pop(i))
print('POP Finished')
else:
print('POP Failed')
###FIND
elif choose == '3':
FindName = input('Name: ')
if FindName in Stack:
print('%s is in %s' %(FindName,Stack))
print('')
else:
print('Not Found')
###LENGTH
elif choose == '4':
if len(Stack):
length = len(Stack)
print('%s Length is %s' %(Stack,length))
else:
print('Stack Empty')
elif choose == '5':
if len(Stack):
print('Empty')
elif choose == '6':
break
else:
print('Input right choose')
测试结果:
第二种:
stack = []
info = """
栈操作
1.入栈
2.出栈
3.栈顶元素
4.栈的长度
5.栈是否为空
q.退出
"""
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('请输入正确的选择')