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