利用python列表的操作,利用菜单的形式实现栈和队列
栈:
stack=[]
def push():
stack.append(input('enter: ').strip())
def pop():
if len(stack)==0:
print('connot pop from an empty stack')
else :
print('Remove[',stack.pop(),']')
def viewstack():
print(stack)
CMDS={'u':push,'o':pop,'v':viewstack}
def showmenu():
pr="""
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter chioce: """
while True:
while True:
try:
choice=input(pr).strip()[0].lower()
except(EOFError,KeyboardInterrupt,IndexError):
choice='q'
print('\nYour choice [%s]' % choice)
if choice not in 'uvoq':
print('Invalid option!')
else :
break
if choice=='q':
break
CMDS[choice]();
if __name__=='__main__':
showmenu()
队列:
#queue of python
#author:gaolee
queue=[]
def push():
queue.append(input('Enter :').strip())
def pop():
if len(queue)==0:
print('Cannot pop from an empty queue')
else:
print('Remove [ ',queue.pop(0),' ]')
def viewQ():
print(queue)
menu={'e':push,'d':pop,'v':viewQ}
def showmenu():
pr="""
(E)nqueue
(D)equeue
(V)iewQ
(Q)uit
Enter chioce: """
while True:
while True:
try:
choice=input(pr).strip()[0].lower()
except(EOFError,KeyboardInterrupt,IndexError):
choice='q'
print('\nYour choice [%s]' % choice)
if choice not in 'edvq':
print('Invalid option!')
else :
break
if choice=='q':
break
menu[choice]();
if __name__=='__main__':
showmenu()