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

    原文作者:停车场模拟问题
    原文地址: https://blog.csdn.net/u012016940/article/details/39104951
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞