python实现栈和队列

本文通过Python列表操作,以菜单形式实现了栈和队列的数据结构。栈支持压栈、弹栈及查看栈内容;队列支持入队、出队及查看队列内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值