Python模拟栈 和 队列


模拟Queue
 #!/usr/bin/python

import sys

queue = []
def enQueue( data ):
    queue.append( data )

def deQueue():
    if len(queue) == 0:
        print "No data in the queue!"
    else:
        val = queue.pop(0)
        print "The dequeue data is %s" % val

def viewQueue():
    print queue

def showMenu():
    menu = """
        E(enQueue)
        D(deQueue)
        V(View)
        Q(Quit)
        Enter you choice:"""

    done = 0
    while not done:
        select = 0
        while not select:
            choice = raw_input(menu)[0]
            print "\n Your choice is [%s]" % choice
            if choice not in "EDVQ":
                print "Error in select,please try again!"
            else:
                select = 1
        if choice == "Q":
            sys.exit(1)
        if choice == "E":
            val = int(raw_input("Please enter a number:"))
            enQueue(val)
        if choice == "D":
            deQueue()
        if choice == "V":
            viewQueue()

if __name__ == "__main__":
     showMenu()



Stack
#!/usr/bin/python
import sys

stack = []

def pushData( data ):
    stack.append(data)

def popData():
    if len(stack)==0:
        print "Can not pop data from stack!"
    else:
        data = stack.pop()
        print "The pop data is %s" % data

def viewStack():
    print stack

def showMenu():
    listMenu = """
        U (push)
        O (pop)
        V (view)
        Q (quit)
        Enter your choice:"""
    done = 0
    while not done:
        select = 0
        while not select:
            choice = raw_input(listMenu)[0]
            print "\nYou select:[%s]" % choice
            if choice not in "UOVQ":
                print "Error selection please select again!"
            else:
                select = 1
            if choice == "Q":
                sys.exit(1)
            if choice == "U":
                data = int(raw_input("Please enter a number:"))
                pushData(data)
            if choice == "O":
                popData()
            if choice == "V":
                viewStack()

if __name__ == "__main__":


Python的优美  胜于C/C++,JAVA etc....


QQ编程群交流: 204944806
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值