Implementing a queue |
0 | Charlotte | 1 |
1 | Fred | 2 |
2 | Bert | x |
3 | 4 | |
4 | 5 | |
5 | 6 | |
6 | 7 | |
7 | 8 | |
8 | 9 | |
9 | x |
- HeadOfQueue = 1
- FreeSpace = 3
A queue is First in first out. This means that we can not add or remove nodes in the middle of the queue. The algorithims for adding / removing are
Adding
- Look at the node pointed to by the "HeadOfQueue" pointer
- Follow the pointers until you reach the end of the queue.
- Make this pointer point to "freeSpace" (the start of the free space queue)
- Add the data to the node pointed to by "freeSpace"
- Set the "FreeSpace" pointer to be the next free node (follow the pointer from the new node)
- Set the new nodes pointer to be x (or null)
Removing
- If the HeadOfQueue points to null then return a erorr (i.e. the queue is empty)
- Start at the HeadOfQueue
- Set the nodes pointer to be the same as "FreeSpace"
- HeadOfQueue will be copied over to the FreeSpace