The queue structure can be modeled using an array, with only two markers for the head and tail to be set
Reference from "Aha"
1 #The code in the book will be indexed out of bounds (the book has applied for excessive space)2 #try to initialize the Tai to Len (q)-1 without error but with the last one missing3 #by exception handling, capturing out-of-bounds exceptions jumps directly out of the loop4 defQueue_demo1 (q):5Newq = []6Head =07tail = len (q)#record queue last one8 9 whileHead <Tail:Ten newq.append (Q[head]) OneHead + 1 A Try: - q.append (Q[head]) - exceptIndexerror: the Break -Head + 1 -Tail + = 1 - + returnNewq
The use of specific methods and considerations, the following different ways of implementation is the same truth:
if __name__=="__main__":#Note that inserting inserts and deleting del operations outside of the list tail is time-consuming#best to use only append or extendQ= List ("631758924")#separating string sequencesNewq =Queue_demo (q)PrintNewq>>> ['6','1','5','9','4','7','2','8','3']
We can also implement the queue type ourselves:
1 #======= Manually implementing the queue type =======2 #Queue node Element3 classNode:4 def __init__(self,data,next=None):5Self.data =Data6Self.next =Next7 8 #simple FIFO queue category9 classQueue:Ten def __init__(self): OneSelf.head =None ASelf.tail =None -Self.count =0 - the defAppend (self,data): - ifSelf.head = =None: -Self.head =Node (data) -Self.tail =Self.head + Else: -Self.tail.next =Node (data) +Self.tail =Self.tail.next ASelf.count + = 1 at - defpop (self): - ifSelf.head = =None: - Raise "Error:head==none" -data =Self.head.data -Self.head =Self.head.next inSelf.count-= 1 - returnData to + #new implementation of the above algorithm - defQueue_demo2 (q): the *Queue =Queue () $ forIteminchQ:#Initialize QueuePanax Notoginseng queue.append (item) - theNewq = [] + whileQueue.count >0: ANewq.append (Queue.pop ())#record the deleted element the ifqueue.count==0: + Break - Else: $temp = Queue.pop ()#elements from the new queue $ queue.append (temp) - - returnNewq
Python provides a built-in data structure in the collections module
#using Python built-in objects#deque: Double-ended queue that can quickly append and insert objects from both sides#Note that list.pop (0) can also pop up the first element, but it's actually time-consuming.defQueue_demo3 (q): fromCollectionsImportdeque#good, suddenly found that their own method of writing and built-in object name exactly the same, the code does not have to change #I also guess the above ...Queue =deque () forIteminchQ:#Initialize Queuequeue.append (item) NEWQ= [] whileQueue.count >0:newq.append (Queue.pop ())#record the deleted element ifqueue.count==0: Break Else: Temp= Queue.pop ()#elements from the new queuequeue.append (temp)returnNewq
Python data structures and algorithms--queues