Basic concepts of stack and queue data structures and their associated Python implementations

Source: Internet
Author: User
Let's review the basic concepts of stacks and queues:

The same point: from the "Data structure" point of view, they are all linear structures, that is, the relationship between the data elements is the same.

The difference: A stack is a linear table that restricts insertions and deletions only at one end of the table. A queue is a linear table that qualifies only one end of a table to be inserted and deleted at the other. They are completely different data types. In addition to their respective basic set of operations, the main difference is the "qualification" of the insert and delete operations.

The stack must be operated in the "last in First out" rule: for example, the primary school teacher corrects the student's homework, if does not disturb the order of the exercise books, then the teacher corrects the first assignment must be the final student to hand in that job, if all the exercise books as a stack of elements, Then the last classmate handed the exercise is the top of the stack, and the first classmate, that is, the lowest end of the exercise, is the bottom of the stack element, which is the stack of reading rules.

The queue must be operated in "FIFO" rules: for example, some people go to the bank for business, must first go to the queue to get the service, of course he is the first to walk out of the bank (assuming these people are in a window queue). If you think of all the people waiting for the service as the elements of the team, the first person is the right element, the corresponding, the last person is the end of the team element. This is the team's read rule.


Using Python to implement the stack, this is an example of Python's core programming:

#!/usr/bin/env python #定义一个列表来模拟栈 stack = [] #进栈, the Append () function of the invocation list is added to the end of the list, strip () No parameters are stripped-down spaces def pushit (): Stack.append  (Raw_input (' Enter new string: '). Strip ()) #出栈, using the Pop () function Def popit (): If Len (stack) = = 0:print ' cannot pop from an   Empty stack! ' Else:print ' Removed [', Stack.pop (), '] ' #编历栈 def viewstack (): print stack #CMDs是字典的使用 CMDs = {' U ': pushit, ' O ': Popit, ' V ': viewstack} #pr为提示字符 def showmenu (): PR = "" "P (U) SH p (O) p (v) iew (Q) uit Enter choice:" "wh Ile true:while True:try: #先用strip () Remove the space and convert the first character to lowercase choice = raw_input (pr). Strip () [0].lower (       ) except (Eoferror, Keyboardinterrupt, indexerror): choice = ' q ' print ' \nyou picked: [%s] '% choice If choice not in ' uovq ': print ' Invalid option, try again ' else:break #CMDs [] According to the input choice from the dictionary Corresponding value, such as input u, from the dictionary to get value of Pushit, execute Pushit () into the stack operation if choice = = ' Q ': Break Cmds[choice] () #判断是否是从本文件进入, not is called if__name__ = = ' __main__ ': ShowMenu ()  

To implement a queue with Python:

#!/usr/bin/env python  queue = []  def EnQ ():   queue.append (Raw_input (' Enter new string: '). Strip ())  # The pop () function that invokes the list of lists. Pop (0) is the first element of the list Def DeQ ():   If len (queue) = = 0:     print ' cannot pop from an empty queue! '   else:     print ' Removed [', Queue.pop (0), '] '  def viewq ():   print queue  CMDs = {' E ': EnQ, ' d ': DeQ, ' V ': view Q}  def showmenu ():   PR = "" "   (E) nqueue   (D) equeue   (V) iew   (Q) uit     Enter choice:" "" While    true: while     true:       try:         choice = raw_input (pr). Strip () [0].lower ()       except (Eoferror, Keyboardinterrupt, Indexerror):         choice = ' Q '        print ' \nyou picked: [%s] '% choice       if choice not in ' Devq ': 
  print ' Invalid option, try again '       else:         break     if choice = = ' Q ': Break     Cmds[choice] ()  if __name__ = = ' __main__ ':   
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.