As a programmer, you only have to worry about the top element in the queue and the last element. This is because you will enqueue, or add items to the end of the queue, and dequeue, or remove the first, or top, element of the queue.
When you add an item to the queue, you find the last element and you perform some basic code like you would see below in this pseudocode:
function void enqueue ( Element last, Element newItem) {
last.nextElement = newItem;
last = newItem;
}
Notice that you don’t have to return anything. You are just putting items into your list, and you update a pointer to the last item, so you automatically know where it is. This is for speed of operations. You could navigate through the linked list, and for a short list it wouldn’t take much time. However, if your list became backed up and had tens of thousands of items in it, it could be a time consuming process.
Removing an element is just as easy.
function Element dequeue() {
Element temp = top;
top = top.nextElement;
return temp;
}
In a traditional queue, we don’t ever have to worry about items outside of the first and last element. Some queues don’t even provide a method to count, although that is relatively easy since if you look at it, the way we store data is very familiar. Specifically, it’s a linked list. We are just limiting access to adding and removing items so that becomes a queue.
Potential Issues
Now there is some potential issues with the psuedocode listed here. For example, we never test to see if our queue doesn’t have any elements. A test is simple, but what should we do? Throw an exception? Return null? These are questions we have to think about as we develop applications.
Programming a Queue was originally found on Access 2 Learn