Download - Data Structures( 数据结构 ) Course 5:Queue
Data Structures(Data Structures( 数据结数据结构构 ))
Course 5:QueueCourse 5:Queue
2西南财经大学天府学院
VocabularyVocabulary
queue 队列 enqueue 进队 dequeue 出队 queue front 队头 queue rear 队尾 Queuing theory 排队论
3西南财经大学天府学院
5.1 5.1 Queue OperationsQueue Operations
A queue is a linear list in which data can be inserted at one end, called the rear, and deleted from the other end, called the front. It is a first in-first out (FIFO) data structure.
front rear
Remove(dequeue)
A computer queue
(Enqueue)
4西南财经大学天府学院
Enqueue: Enqueue inserts an element at the rear of the queue.
plum kiwi
front rear EnqueueEnqueueplum grape
front rear
kiwi
grapedata
Queue OperationQueue
Dequeue: Dequeue deletes an element at the front of the queue.
kiwi
front rearDequeueDequeueplum grape
front rear
kiwi
plumdata
Queue Operation Queue
grape
5西南财经大学天府学院
Queue Front: Queue front examines the element at the front of the queue.
plum grape
front rear
kiwi
Queue
plum grape
front rear
kiwi
Queue
Queuefront
Queuefront
plum data
Operation
Queue Rear: Queue rear examines the element at the rear of the queue.
plum grape
front rear
kiwi
Queue
plum grape
front rear
kiwi
Queue
Queuerear
Queuerear
grape
data
Operation
6西南财经大学天府学院
5.2 5.2 Queue Linked List Queue Linked List DesignDesign
Data structure: For the linked list implementation of a queue, we use tow types of structures: a head and a node.
Queue head: The queue head contains the two pointers and a count of the queue.Queue data node: The queue data node contains the user data and a link field pointing to the next node .
7西南财经大学天府学院
plum kiwi grape figfront rear
Conceptual queue
plum kiwi grape fig
front rear
4
front rear
Physical queue
front rearcount data next
Head structure Node structure
8西南财经大学天府学院
Queue AlgorithmsCreate queue: set the metadata pointers to null and the count to 0.
? ? ?
front rearcount
Before
0
front rearcount
After
No queue
Algorithm createQueue (ref queue <metadata>1 queue.fornt = null2 Queue.rear = null3 Queue.count = 0End createQueue
Algorithm createQueue (ref queue <metadata>1 queue.fornt = null2 Queue.rear = null3 Queue.count = 0End createQueue
9西南财经大学天府学院
Enqueue: Three conditions need to be considered: 1.insert into an empty queue. 2. Insert into a queue with data. 3. Insertinto a queue when there is no memory left in the heap.
0
front rearcount
plumnextdata
plumnextdata
newPtr newPtr
1
front rearcount
Before AfterInsert into empty queue
10西南财经大学天府学院
plum
nextdata
1
front rearcount
kiwi
nextdata
newPtr
plumnextdata
2
front rearcount
kiwinextdata
newPtr
Before
After
Insert into queue with data
Algorithm enqueue (ref queue<metadata> dataIn <dataType>1 If (queue full) 1 return false2 End if3 Allocate (newPtr)4 newPtr->data = dataIn5 newPtr->next = null pointer6 If (queue.count zero) // inserting into null queue 1 queue.front = newPtr7 Else // insert data 1 queue.rear->next = newPtr8 End if9 Queue.rear = newPtr10 Queue.count = queue.count + 111 Return trueEnd enqueue
Algorithm enqueue (ref queue<metadata> dataIn <dataType>1 If (queue full) 1 return false2 End if3 Allocate (newPtr)4 newPtr->data = dataIn5 newPtr->next = null pointer6 If (queue.count zero) // inserting into null queue 1 queue.front = newPtr7 Else // insert data 1 queue.rear->next = newPtr8 End if9 Queue.rear = newPtr10 Queue.count = queue.count + 111 Return trueEnd enqueue
There are four ways to test if the queue is null 1.Front null2.Rear null3.Count 04.Emptyqueue
11西南财经大学天府学院
Dequeue: 1. Ensure that the queue contains data.2. Pass the data back through the parameter list and
then set the front pointer to the next item in the queue.
3. If the queue is now empty, set the rear pointer to null.
plumnextdata
1
front rearcount
0
front rearcount
deleteLoc(recycled)
BeforeAfter
Delete only item in queue
12西南财经大学天府学院
plumnextdata
2
front rearcount
kiwinextdata
Before
plumnextdata
1
front rearcount
kiwinextdata
(recycled)
deleteLoc After
Algorithm dequeue (ref queue <metadata> ref item <dataType>)1 If (queue.count is 0) 1 return false2 End if3 Item = queue.front->data4 deleteLoc = queue.front5 If (queue.count 1)
// Delete only item in queue 1 queue.rear = null pointer6 End if7 Queue.front = queue.front->next8 Queue.count = queue.count – 19 Recycle (deleteLoc)10 Return trueEnd dequeue
Algorithm dequeue (ref queue <metadata> ref item <dataType>)1 If (queue.count is 0) 1 return false2 End if3 Item = queue.front->data4 deleteLoc = queue.front5 If (queue.count 1)
// Delete only item in queue 1 queue.rear = null pointer6 End if7 Queue.front = queue.front->next8 Queue.count = queue.count – 19 Recycle (deleteLoc)10 Return trueEnd dequeue
13西南财经大学天府学院
Retrieving Queue Data: the logic of retrieving data is the same to that of dequeue except that the data are not deleted from the queue.
Algorithm queueFront ( val queue <metadata>, ref dataOut <dataType>)1 If (queue.count is 0) 1 return false2 End if3 dataOut = queue.front->data4 Return trueEnd queueFront
Algorithm queueFront ( val queue <metadata>, ref dataOut <dataType>)1 If (queue.count is 0) 1 return false2 End if3 dataOut = queue.front->data4 Return trueEnd queueFront
14西南财经大学天府学院
Empty Queue: it returns true if the queue is empty and false if the queue contains data.Algorithm emptyQueue ( val queue <metadata>)
1 Return (queue.count equal 0)End emptyQueue
Algorithm emptyQueue ( val queue <metadata>)1 Return (queue.count equal 0)End emptyQueue
Full Queue: By allocating a node and then releasing the memory we can determine whether there is room for at least one more node.
Algorithm fullQueue ( val queue <metadata>)1 Allocate (tempPtr)2 If (allocate successful) 1 recycle (tempPtr) 2 return false3 Else 1 return true4 End ifEnd fullQueue
Algorithm fullQueue ( val queue <metadata>)1 Allocate (tempPtr)2 If (allocate successful) 1 recycle (tempPtr) 2 return false3 Else 1 return true4 End ifEnd fullQueue
15西南财经大学天府学院
Destroy Queue: it deletes all data in the queue and recycles their memory.
Queue Count: it returns the number of elements currently in the queue by returning the count found in the queue head node.
Algorithm Queuecount ( val queue <metadata>)1 Return (queue.count)End queueCount
Algorithm Queuecount ( val queue <metadata>)1 Return (queue.count)End queueCount
Algorithm destroyQueue ( ref queue <metadata>)1 pWalker = queue.front2 Loop (pWalker not null) 1 deletePtr = pWalker 2 pWalker = pWalker.next 3 recycle (deletePtr)3 End loop4 Queue.front = null5 Queue.rear = null6 Queue.count = 07 returnEnd destroyQueue
Algorithm destroyQueue ( ref queue <metadata>)1 pWalker = queue.front2 Loop (pWalker not null) 1 deletePtr = pWalker 2 pWalker = pWalker.next 3 recycle (deletePtr)3 End loop4 Queue.front = null5 Queue.rear = null6 Queue.count = 07 returnEnd destroyQueue
16西南财经大学天府学院
5.3 5.3 Queuing TheoryQueuing TheoryQueuing theory is a field of applied mathematics that is used to predict the performance of queues.
A Single-server queue can provide service to only one customer at a time.
Example: the hot-food vendor.A Multi-server queue can provide service to many customers at a time.
Example: a bank in which there is one line with many bank tellers providing service.
17西南财经大学天府学院
Two elements to all queuesA customer is any person or thing needing service. Such as jobs in computer, packages being sent…The service is any activity needed to accomplish the required result.
Two factors affect the queueThe arriving rate( 比率 ) is the rate at which customers arrive in the queue for service. Depending on the service being provided, the arrival rate may be random or regular.Service time is the average time required to complete the processing of a customer request.The arriving rate and service time are the factors that most affect the performance of queues.
18西南财经大学天府学院
The faster customers arrive and the higher the service time, the longer the queue will be.The ideal is arrival rate matches service time The importance of queuing theory: it can predict the queue patterns including queue time(that is, the average length of time customers wait in the queue), the average size of the queue, and the maximum queue size. So, we can build a model of queue and used the model to study proposed changes to the system.For example, In the banking queue, if we were able to add automation improvements that would reduce the average service by 15%,how many fewer tellers would we need?
19西南财经大学天府学院
ServerQueue
Queuetime
Servicetime
Responsetime
A queuing theory model
20西南财经大学天府学院
5.4 5.4 Queue ApplicationsQueue Applications
Two queue implementations: Queue simulation and categorizing data Queue simulation: a modeling activity used to generate statistics about the performance of queues.An example: a saltwater taffy store on a beach boardwalk. The store has one window and a clerk can service only one customer at a time. The store also ships boxes of taffy anywhere in the country.The time to serve customers varies between 1 and 10 minutes.(8hs per day, 7 days a week)
21西南财经大学天府学院
Events: completed process new customer module: determine the arrival of a new customer. The owner found that, on average , a customer arrives every 4 minutes. An arrival rate is simulated by using a random number generator that returns a values between 1 and 4. If = 4, customer arrived; 1,2,3 customer not arrived.server free module: determine whether the clerk is busy or idle. If the clerk is idle, then the next waiting customer in line can be served. If the clerk is busy, then the waiting customers remain in the queue.Completed processing: determine whether it has completed processing for the current customer. Then processing time for the current customer is determined by a random number generator when the processing is started. When customers has been completely served, we gather statistics about sale and set server to an idle state
22西南财经大学天府学院
Data structures: Four data structure are required for the queue simulationQueue head: It contains two node pointers – front and rear – and a count of the number of elements currently in the queue.Queue node: It contains the customer data and a next node pointer. The customer data consist of a sequential customer number and the arrival time.Current Customer status: We use customer’s number, arrival time, the start time and the processing time to describe customer status.(random generator to calculate)Simulation statistics: It stores the total number of customers processed in the simulation, the total and average service time, the total and average wait time, and the maximum number of customers in the queue at one time.
23西南财经大学天府学院
2front rearcount
nextcustNum arriveTime
custNum arriveTime startTime svcTime
numCust totSvcTime totWaitTime maxQueueSize
simStats
custStatus
node
head
Figure 5-13 queue data structures
24西南财经大学天府学院
Output: the statistics gathered during the simulation and the average queue wait time and average queue service time, the basic statistics for each customer: arrival time, start time, wait time, service time etc.
Simulator
Printstats
Newcustomer
Serverfree
Service complete
Createqueue
Figure 5-14 design for queue simulation
25西南财经大学天府学院
Simulation AlgorithmSimulator
Algorithm taffySimulationData Structures data number <integer> arrivalTime <integer> end data head front <node pointer> count <integer> rear <node pointer> end head node custData <data> next <node pointer> end node
Algorithm taffySimulationData Structures data number <integer> arrivalTime <integer> end data head front <node pointer> count <integer> rear <node pointer> end head node custData <data> next <node pointer> end node
custStatus custNum <integer> arriveTime <integer> startTime <integer> svcTime <integer> end custstatus simStats numCust <integer> totSvcTime <integer> totWaitTime <integer> maxQueueSize <integer> end simstats
custStatus custNum <integer> arriveTime <integer> startTime <integer> svcTime <integer> end custstatus simStats numCust <integer> totSvcTime <integer> totWaitTime <integer> maxQueueSize <integer> end simstats
26西南财经大学天府学院
Statements1 CreateQueue (queue)2 Clock = 13 endTime = 8*604 custNum = 05 Loop (clock <=endTime or moreCusts) 1 newCustomer (queue, clock, custNum) 2 serverFree (queue, clock, custStatus, moreCusts) 3 svcComplete (queue, clock, custStatus, runStats, moreCusts) 4 if ( not emptyQueue (queue)) 1 moreCusts = true 5 end if 6 clock = clock + 16 End loop7 printStats (runStats)8 return end taffySimulation
Statements1 CreateQueue (queue)2 Clock = 13 endTime = 8*604 custNum = 05 Loop (clock <=endTime or moreCusts) 1 newCustomer (queue, clock, custNum) 2 serverFree (queue, clock, custStatus, moreCusts) 3 svcComplete (queue, clock, custStatus, runStats, moreCusts) 4 if ( not emptyQueue (queue)) 1 moreCusts = true 5 end if 6 clock = clock + 16 End loop7 printStats (runStats)8 return end taffySimulation
Algorithm 5-9 queue simulation: driver
27西南财经大学天府学院
New customer
Algorithm newCustomer (ref queue < metadata >, val clock <integer>, ref custNum <integer>)1 Arrival = (random number modulo 4) + 12 If (arrival equal 4) // new customer has arrived 1 custNum = custNum + 1 2 custData.number = custNum 3 custData.arriveTime = clock 4 enqueue (queue, custData)3 End if4 ReturnEnd newCustomer
Algorithm newCustomer (ref queue < metadata >, val clock <integer>, ref custNum <integer>)1 Arrival = (random number modulo 4) + 12 If (arrival equal 4) // new customer has arrived 1 custNum = custNum + 1 2 custData.number = custNum 3 custData.arriveTime = clock 4 enqueue (queue, custData)3 End if4 ReturnEnd newCustomer
28西南财经大学天府学院
Server free
Algorithm serverFree ( ref queue <metadata>, val clock <integer> , ref status <custStastus>, ref moreCusts <Boolean> )1 If (clock > status.startTime + status.svcTime – 1) // server is idle 1 if (not emptyQueue (queue)) 1 dequeue (queue,custData) 2 status.custNum = custData.number 3 status.arriveTime = custData.arriverTime 4 status.startTime = clock 5 status.svcTime = random service time 6 moreCusts = true 2 end if2 End if3 ReturnEnd serverFreestatus
Algorithm serverFree ( ref queue <metadata>, val clock <integer> , ref status <custStastus>, ref moreCusts <Boolean> )1 If (clock > status.startTime + status.svcTime – 1) // server is idle 1 if (not emptyQueue (queue)) 1 dequeue (queue,custData) 2 status.custNum = custData.number 3 status.arriveTime = custData.arriverTime 4 status.startTime = clock 5 status.svcTime = random service time 6 moreCusts = true 2 end if2 End if3 ReturnEnd serverFreestatus
29西南财经大学天府学院
Service complete
Algorithm svcComplete (ref queue <metadata>, val clock <integer>, ref status <custStatus>, ref stats <simStats>, ref moreCusts <Boolean>)1 If (clock equal status.startTime + status.svcTime – 1) //current call complete 1 waitTime = status.startTime – status.arriveTime 2 stats.numCust = stats.numCust + 1 3 stats.totSvcTime = stats.totSvcTime + status.svcTime 4 stas.totWaitTime = stats.totWaitTime + waitTime 5 queueSize = queueCount (queue) 6 if (stas.maxQueueSize < queueSize) 1 stats.maxQueueSize = queueSize 7 end if 8 print ( status.custNum status.arriveTime status.startTime status.svcTime waitTime queueCount(queue)) 9 moreCusts = false2 ReturnEnd svcComplete
Algorithm svcComplete (ref queue <metadata>, val clock <integer>, ref status <custStatus>, ref stats <simStats>, ref moreCusts <Boolean>)1 If (clock equal status.startTime + status.svcTime – 1) //current call complete 1 waitTime = status.startTime – status.arriveTime 2 stats.numCust = stats.numCust + 1 3 stats.totSvcTime = stats.totSvcTime + status.svcTime 4 stas.totWaitTime = stats.totWaitTime + waitTime 5 queueSize = queueCount (queue) 6 if (stas.maxQueueSize < queueSize) 1 stats.maxQueueSize = queueSize 7 end if 8 print ( status.custNum status.arriveTime status.startTime status.svcTime waitTime queueCount(queue)) 9 moreCusts = false2 ReturnEnd svcComplete
30西南财经大学天府学院
Algorithm printStats ( stats <simStats> )1 Print (Simulation Statistics: )2 Print (Total customers: stats.numCust)3 Print (Total service time: stats.totSvcTime)4 avrgSvcTime = stats.totSvcTime / stats.numCust5 Print (Average service time: arvgSvcTime)6 avrgWaitTime = stats.totWaitTime / stats.numCust7 Print (Average wait time: avrgWaitTime)8 Print (,Maximum queue size: stats.maxQueueSize)9 returnEnd printstats
Algorithm printStats ( stats <simStats> )1 Print (Simulation Statistics: )2 Print (Total customers: stats.numCust)3 Print (Total service time: stats.totSvcTime)4 avrgSvcTime = stats.totSvcTime / stats.numCust5 Print (Average service time: arvgSvcTime)6 avrgWaitTime = stats.totWaitTime / stats.numCust7 Print (Average wait time: avrgWaitTime)8 Print (,Maximum queue size: stats.maxQueueSize)9 returnEnd printstats
Print stats
31西南财经大学天府学院
Categorizing Data: It is often necessary to rearrange data without destroying their basic sequence. For example, given the following list of numbers
3 22 12 6 10 34 65 29 9 30 81 4 5 19 20 57 44 99
then categorize them into four different groups:
Group1: less than 10
Group2: between 10 and 19
Group3: between 20 and 29
Group4: 30 and greater
3 6 9 4 5 12 10 19 22 29 20 34 65 30 81 57 44 99
32西南财经大学天府学院
Algorithm categorize
1 CreateQueue (q0to9)
2 createQueue (q10to19)
3 createQueue (q20to29)
4 createQueue (qOver29)
5 fillQueues (q0t09, q10to19,q20to29, qOver29)
6 printQueues (q0to9, q10to19, q20to29,qOver29)
7 Return
End categorize
Algorithm categorize
1 CreateQueue (q0to9)
2 createQueue (q10to19)
3 createQueue (q20to29)
4 createQueue (qOver29)
5 fillQueues (q0t09, q10to19,q20to29, qOver29)
6 printQueues (q0to9, q10to19, q20to29,qOver29)
7 Return
End categorize
33西南财经大学天府学院
Algorithm fillQueues (ref q0to9 <metadata>, ref q10to19 <metadata>, ref q20to29 <metadata>, ref qOver29 <metadata>)1 Loop (not EOF) 1 read (number) 2 if (number < 10) 1 enqueue (q0to9, number) 3 elseif (number<20) 1 enqueue (q10to19, number) 4 elseif (number<30) 1 enqueue (q20to29, number) 5 else 1 enqueue (qOver29, number) 6 end if2 End loop3 ReturnEnd fillQueue
Algorithm fillQueues (ref q0to9 <metadata>, ref q10to19 <metadata>, ref q20to29 <metadata>, ref qOver29 <metadata>)1 Loop (not EOF) 1 read (number) 2 if (number < 10) 1 enqueue (q0to9, number) 3 elseif (number<20) 1 enqueue (q10to19, number) 4 elseif (number<30) 1 enqueue (q20to29, number) 5 else 1 enqueue (qOver29, number) 6 end if2 End loop3 ReturnEnd fillQueue
34西南财经大学天府学院
5.8 5.8 SummarySummary
A queue is a linear list in which data can only be inserted at one end, called the rear, and deleted from the other end, called the front.A queue is a first in-first out (FIFO) structure.There are four basic queue operations: enqueue, dequeue, queue front, and queue rear.
The enqueue operation inserts an element at the rear of the queue.The dequeue operation deletes the element at the front of the queue.The queue front operation examines the element at the front of the queue without deleting it.The queue rear operation examines the element at the rear of the queue without deleting it.
35西南财经大学天府学院
To implement the queue using a linked list, we use two types of structures: a head and a node.Queuing theory is a field of applied mathematics that is used to predict the performance of queues.Queue applications can be divided into single servers and multi-servers.
A single-server queue application provides service to only one customer at a time.A multi-server queue application provides service to only several customers at a time.
The two features that most affect the performance of queues are the arrival rate and the service time.
The rate at which the customers arrive in the queue for service is known as the arrival rate.Service time is the average time required to complete the processing of a customer request.
36西南财经大学天府学院
The queue time is the average length of time customers wait in the queue.The response time is a measure of average time from the point at which customers enter the queue until the moment they leave the server. It is queue time plus service time.One application of queues is queue simulation, which is a modeling activity used to generate statistics about the performance of a queue.Another application of queues is categorization. Queues are used to categorize data into different groups without losing the original ordering of the data.Queues can be implemented suing linked lists or arrays.
37西南财经大学天府学院
ExerciseExercise
Imagine you have a stack of integers,S ,and a queue of integers,Q. Draw a picture of S and Q after the following operation:PushStack(S,3)PushStack(S,12)Enqueue(Q,5)Enqueue(Q,8)PopStack(S,x)pushStack(S,2)Enqueue(Q,x)Dequeue(Q,y)PushStack(S,x)PushStack(S,y)
38西南财经大学天府学院
ExerciseExercise
What would be the contents of queue Q1 and Q2 after the following code is executed and the following data are entered?Q1=createQueueQ2=createQueueLoop (not end of file)
read numberenqueue(Q1,number)enqueue(Q2,number)loop (Not empty Q1)dequeue(Q1,x)enqueue(Q2,x)End loop
End loop The data are 5,7,12,4,0,4,6