Python data structure and algorithm 14 queue python implementation

Source: Internet
Author: User

Python Implementation of queue

After an abstract data type is created, a class can be created to implement the queue. As before, we used the python built-in list as a tool to create a queue class.

The queue is also ordered, so it is necessary to determine which end of the queue is used as the frontend and tail end of the queue. In the following implementation code, we agree that the 0 position of the list is the end of the queue. The advantage is that the list insert method can be directly used to add data at the end of the team, use pop to delete data at the front end of the queue (the last data in the list. From the performance analysis, this means that the endueue is O (n), and the departure is O (1 ).

Listing 1

Class Queue:

Def _ init _ (self ):

Self. items = []

Def isEmpty (self ):

Return self. items = []

Def enqueue (self, item ):

Self. items. insert (0, item)

Def dequeue (self ):

Return self. items. pop ()

Def size (self ):

Return len (self. items)

The following is the test code.

Q = Queue ()

Q. isEmpty ()

Q. enqueue ('Dog ')

Q. enqueue (4)

Q = Queue ()

Q. isEmpty ()

Q. enqueue (4)

Q. enqueue ('Dog ')

Q. enqueue (True)

After running the code, you can test the following functions on the console:

>>> Q. size ()

3

>>> Q. isEmpty ()

False

>>> Q. enqueue (8.4)

>>> Q. dequeue ()

4

>>> Q. dequeue ()

'Dog'

>>> Q. size ()

2


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.