Programming – Pascal: Essential skills 7
Learning Outcomes:
- Construct lists, stacks and queues in terms of arrays.
- Students should be able to create and manipulate linear linked lists, stacks and queues in terms of arrays.
Data structure - Queue
Features of a queue:
- First-in-first-out i.e. moving an item can only be from the front(head) and adding an item can only be to the end(tail).
A queue represented by an array:
- Inconvenient to move every items forward when first item is removed. Pointers are used to represent the head and tail positions. I.e. head pointer moves to next location when first item is removed.
- When more and more items are added and removed from the queue, the tail pointer reaches the end of the array. In order to fully utilize the array, the tail pointer move to the first position of the array for the queue to continue. In this way, the array is analogous to a circular array.
- The queue size is limited by the size of the array.
One of the way to implement a queue:
var queue
: array[0..2] of string; (* array
with 3 slots *) head,
tail : integer; begin head := 0; tail := 0; (* when head = tail, queue is
empty *) … |
|
head = 0 |
head = 1 |
head = 2 |
|||
Size of of the queue |
head |
tail |
head |
tail |
head |
tail |
0 |
0 |
0 |
1 |
1 |
2 |
2 |
1 |
0 |
1 |
1 |
2 |
2 |
0 |
2 |
0 |
2 |
1 |
0 |
2 |
1 |
3 |
0 |
0 (3 mod 3) |
1 |
1 |
2 |
2 |
Two ways to handle a ‘full’ array
- Use a counter to count the
number of items in the queue. So even head = tail, we know the queue is not
empty as counted by counter. (max number in the queue is 3)
- Avoid filling up the
array. I.e. avoid the situation of head = tail when the queue is not
empty. (max number in the queue is 2)
Relevant past paper:
DSE ICT Elect B(SP-2017): 2014 1cii,iii,d.