题目要求:

栈的工作原理
    入栈
    出栈
    查看栈顶元素
    栈的长度
    栈是否为空

代码如下:第一种

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('请输入正确的选择')

列表实现栈的工作原理

列表实现栈的工作原理

列表实现栈的工作原理

相关文章:

  • 2022-12-23
  • 2021-11-23
  • 2022-02-05
  • 2021-12-18
  • 2021-11-07
  • 2022-02-07
  • 2021-07-06
猜你喜欢
  • 2021-04-18
  • 2022-12-23
  • 2021-05-17
  • 2021-08-11
  • 2022-01-23
  • 2021-08-16
相关资源
相似解决方案