Python uses the list-based append and pop methods to implement the stack and queue function example, pythonappend
This article describes how to implement the stack and queue functions using the list-based append and pop methods in Python. We will share this with you for your reference. The details are as follows:
# Coding = utf8''' Stack: the stack is a data structure of the last-in-first-out (LIFO. The "push" element on the stack is a common term, which means to add an object to the stack. To delete an element, you can "pop" it out of the stack. Queue: a data type of FIFO. The new elements are added to the end of the queue in the form of "Queuing", and "to" is deleted from the queue header. ''' # Create list def creatList (): initList = [] try: while True: # input element inputItem = raw_input (u "Enter item (input quit end input): ") # When the input character is not quit, add the element to the list # When the input character is quit, end the input if inputItem! = "Quit": initList. append (inputItem. strip () else: break # return the input List return initList except T Exception, e: print "Create List Error :", e # Delete the first element in the List and return the delete element def popTheFirst (List): try: # Check whether an element exists in the List # If an element exists, delete and return the first element # if it does not exist, a prompt is displayed. if len (List)> 0: return List. pop (0) else: print "The list is empty... "failed t Exception, e: print" pop the first item Error: ", e # Delete the last element of the List and return the delete element def popTheLast (List): try: # determining whether an element exists in the list # If an element exists, delete it and return the last element # if it does not exist, a prompt is displayed. if len (List)> 0: # The pop function deletes the return List of the last element by default. pop () else: print "The list is empty... "failed t Exception, e: print" pop the last item Error: ", e # Call The creatList function to create a table listOne = creatList () # output the table creation Information print" The init list: ", listOne # Call The popTheFirst function to delete and return The first element theFirst = popTheFirst (listOne) # output The first element of The current table print" The first item of list :", theFirst # Call the popTheFirst function to delete and return the last element theLast = popTheLast (ListOne) # print "The last item of list :", theLast ''' here, listOne, theFirst, and theLast are global variables. If you change the order of the preceding statements, you will not be able to obtain the expected results. '''
Running result: