Tutorial 4
πΆπ»ββοΈ
Queue
9618 A-Level
i
Note: for AS, the syllabus states you won't be asked to write a queue from scratch - but they do have "fill in the blank" type questions where they give you most of the code and ask you to complete it
For A2, you can be asked to write an entire queue from scratch, including the enqueue and dequeue modules
It may be useful to search (CTRL + F) for "queue" questions in the (combined) past papers
If you find any bugs/edge cases in this code, please contact me
A queue is a FIFO (first-in, first-out) data structure - we will need a pointer to both the front and end of the queue - often called head and tail pointers respectively
There are two operations queues support:
- Enqueue: if the queue is not full, add the element to the end and increment the tail pointer
- Dequeue: if the queue is not empty, remove and return the first element from the queue
There are two types of queue we will look at in this tutorial:
- Linear queue: elements enqueued sequentially - if the tail pointer equals the queue size, we can't add any more elements, even if we have removed others from the front
- Circular queue: elements enqueued sequentially - if the tail pointer equals the queue size and the queue isn't full, then the tail pointer will "wrap around" to the front of the queue, much like a clock wrapping around from hour 12 back to hour 1 when it reaches that time
1
Linear Queue
As stated, while a linear queue is simple, there is a problem - when we dequeue elements, the front pointer is incremented and these indexes hence become unavailable
More detailed comments can be seen in the code
2
Circular Queue
Unlike a linear queue, both the front (head) and end (tail) pointer can wrap-around back to the beginning of the queue, hence we can reuse indexes that we have previously dequeued from
To keep track of whether the queue is full, the easiest way it to just use another variable as a counter storing the number of items currently in the queue - we will increment when we successfully enqueue and decrement when we successfully dequeue
More detailed comments can be seen in the code
Extension details/answers will be added: web server, simulate traffic at traffic lights, keyboard buffer - words split by space