Data Structures and Algorithms (7) - Queue Queue

  • The basis for defining queue

Queue: a kind of data set order. Its characteristics are adding new data items always take place at the end (rear) and remove the existing data items always take place at the other end (head end front), FIFO .

Queue only one entrance, one exit. When the data is queued, first appeared in the tail, with the removal of the first data item, it gradually closer to the first team. Allowed items directly into the team, is not allowed to remove items from the intermediate (association may flow into pipe, line, etc.)

 

 

  •  Queue type abstract data types -python
Queue() Create an empty queue object, the return value Queue object
enqueue(item) Add the item to the tail data item, no return value
dequeue() The first data item is removed from the team, the first team return value data item, the queue is modified
isEmpty() To test whether the queue is empty, the return value of type bool
size() Returns the number of data items in a queue

 

Python with a custom queue:

 1 class Queue:
 2     def __init__(self):
 3         self.items = []
 4 
 5     def isEmpty(self):
 6         return self.items == []
 7 
 8     def enqueue(self, item): #复杂度O(n)
 9         self.items.insert(0,item)
10 
11     def dequeue(self): #复杂度O(1)
12        return self.items.pop()
13 
14     def size(self):
15         return len(self.items)
16 Q = Queue()
17 Q.enqueue(0)
18 Q.enqueue(1)
19 Q.enqueue('a')
20 print(Q.size())
[OUT]
3

Process finished with exit code 0
  • Queue application
  1. Hot potato issue (Joseph problems)

Problem Description : hot hot potato pass, when the drums stop, the hands of a potato needs of children out of the line. (I do not want to just typing along, and direct shots PPT)

 

 Analysis: The use queue to achieve. After using Queue to store all the names participate in the game, the team's first default is owned potato, the game began, the first team of people out of the line, and then immediately to the tail into the team, recorded as a transfer potatoes, passed num times, the first team of people have been removed and no longer into the team, and so forth, until only one person in the queue.

 

 Code:

 1 from queue1 import Queue
 2 
 3 def hotPotato(namelist, num):
 4     simqueue = Queue()
 5 
 6     for name in namelist:
 7         simqueue.enqueue(name)
 8 
 9     while simqueue.size() >1:
10         for i in range(num):
11             simqueue.enqueue(simqueue.dequeue())  #一次传递
12 
13         simqueue.dequeue()
14     return simqueue.dequeue()
15 print(hotPotato(['a','b','c','d','e','f','g'],7))
d

Process finished with exit code 0

Reference: https://www.bilibili.com/video/BV1QJ411w7bB?p=23

Guess you like

Origin www.cnblogs.com/yeshengCqupt/p/12590555.html