python代码:用列表list模拟栈stack
功能:用列表list模拟栈stack
栈stack是一个后进先出(LIFO)的数据结构。
代码来自书《Python核心编程(第二版).pdf》,作者:Wesley J. Chun
第六章 序列
例6.3 用列表list模拟栈stack
栈stack是一个后进先出(LIFO)的数据结构。
#!/usr/bin/python # -*- coding: UTF-8 -*- """ @author: @file:stack.py @time:2022-02-19 21:26 """ # 用列表模拟堆栈 stack = [] def pushit(): stack.append(input(" Enter New String: ").strip()) def popit(): if len(stack) == 0: print("Cannot pop from an empty stack!") else: print("Removed [", repr(stack.pop()), "]") def viewstack(): print(stack) # calls str() internally CMDs = {"u":pushit, "o":popit, "v":viewstack} def showmenu(): pr = """ p(U)sh p(O)p (V)iew (Q)uit Enter choice: """ while True: while True: try: choice &