






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







After the stack, the next simplest data abstraction is the queue. As with the stack, the queue can be visualized with many examples you are already familiar with from everyday life. A simple illustration is a line of people waiting to enter a theater. The fundamental property of the queue is that items are inserted at one end (the rear of the line) and removed from the other (the door to the theater). This means that the order that items are removed matches the order that they are inserted. Just as a stack was described as a LIFO (last-in, first-out) container, this means a queue can be described as FIFO (first in, first out).
A variation is termed the deque , pronounced “deck”, which stands for d ouble- e nded que ue. In a deque values can be inserted at either the front or the back, and similarly the deck allows values to be removed from either the front or the back. A collection of peas in a straw is a useful mental image. (Or, to update the visual image, a series of tapioca buds in a bubble-tea straw).
Queues and deques are used in a number of ways in computer applications. A printer, for example, can only print one job at a time. During the time it is printing there may be many different requests for other output to be printed. To handle these the printer will maintain a queue of pending print tasks. Since you want the results to be produced in the order that they are received, a queue is the appropriate data structure.
The classic definition of the queue abstraction as an ADT includes the following operations:
addBack (newElement) Insert a value into the queue front() Return the front (first) element in queue removeFront() Remove the front (first) element in queue isEmpty() Determine whether the queue has any elements
The deque will add the following:
addFront(newElement) Insert a value at front of deque back() Return the last element in the queue removeBack() Return the last element in the queue
Notice that the queue is really just a special case of the deque. Any implementation of the deque will also work as an implementation of the queue. (A deque can also be used to implement a stack, a topic we will explore in the exercises).
As with the stack, it is the FIFO (first in, first out) property that is, in the end, the fundamental defining characteristic of the queue, and not the names of the operations. Some designers choose to use names such as “add”, “push” or “insert”, leaving the location unspecified. Similarly some implementations elect to make a single operation that will both return and remove an element, while other implementations separate these two tasks, as well do here. And finally, as in the stack, there is the question of what the effect should be if an attempt is made to access or remove an element from an empty collection. The most common solutions are to throw an exception or an assertion error (which is what we will do), or to return a special value, such as Null.
For a deque the defining property is that elements can only be added or removed from the end points. It is not possible to add or remove values from the middle of the collection.
The following table shows the names of deque and queue operations in various programming languages:
operation C++ Java Perl Pyton insert at front push_front addFirst unshift appendleft Insert at back Push_back addLast Push append remove last pop_back removeLast pop pop remove first pop_front removeFirst shift popleft examine last back getLast $[-1] deque[-1] examine first front getFirst $[0] deque[0]
Given that queues occur frequently in real life, it is not surprising that they are also frequently used in simulations. To model customers using a bank, for example, you could use a queue of waiting patrons. A simulation might want to ask questions such as the how the average waiting time would change if you added or removed a teller position.
Queues are also used in any time collection where time of insertion is important. We have noted, for example, that a printer might want to keep the collection of pending jobs in a queue, so that they will be printed in the same order that they were submitted.
Depth-first and Breadth-first search
Imagine you are searching a maze, such as the one shown at right. The goal of the search is to move from the square marked S, to the square marked F.
A simple algorithm would be the following:
F
S
What is intriguing about the maze-searching algorithm is that the exact same algorithm can be used for both, changing only the underlying data structure. Imagine that we change the stack in the algorithm to a queue:
How to search a maze using breadth-first search : Keep a list of squares you have visited, initially empty. Keep a queue of squares you have yet to visit. Put the starting square in this queue While the queue is not empty: Remove an element from the queue If it is the finish, then we are done Otherwise if you have already visited this square, ignore it Otherwise, mark the square on your list of visited positions, and add all the neighbors of this queue to your stack. If you eventually reach an empty queue and have not found the start, there is no solution
As you might expect, a breadth-first search is more thorough, but may require more time than a depth-first search. While the depth-first search was able to find the solution in 15 steps, the breadth-first search is still looking after 20. The following shows the search at this point. Trace with your finger the sequence of steps as they are visited. Notice how the search jumps all over the maze, exploring a number of different alternatives at the same time. Another way to imagine a breadth-first first is as what would happen if ink were poured into the maze at the starting location, and slowly permeates every path until the solution is reached.
We will return to a discussion of depth-first and breadth-first search in a later chapter, after we have developed a number of other data structures, such as graphs, that are useful in the representation of this problem.
As with the stack, the two most common implementation techniques for a queue are to use a linked list or to use an array. In the worksheets you will explore both of these alternatives.
Worksheet 18 Linked List Queue, Introduction to Sentinels Worksheet 19 Linked List Deque Worksheet 20 Dynamic Array Queue
Building a Linked List Queue
A stack only needs to maintain a link to one end of the chain of values, since both insertions and removals occur on the same side. A queue, on the other hand, performs
17 12 9 7 18 13 4 19 14 5 2
16 11 8 6 0
15 10 3 1
insertions on one side and removals from the other. Therefore it is necessary to maintain a links to both the front and the back of the collection.
FirstLink = LastLink =
2 4 3 7 5
We will add another variation to our container. A sentinel is a special link, one that does not contain a value. The sentinel is used to mark either the beginning or end of a chain of links. In our case we will use a sentinel at the front. This is sometimes termed a list header. The presence of the sentinel makes it easier to handle special cases. For example, the list of links is never actually empty, even when it is logically empty, since there is always at least one link (namely, the sentinel). A new value is inserted after the end, after the element pointed to by the last link field. Afterwards, the last link is updated to refer to the newly inserted value.
Values are removed from the front, as with the stack. But because of the sentinel, these will be the element right after the sentinel.
You will explore the implementation of the queue using linked list techniques in Worksheet 18.
You may have noticed that removal from the end of a ListQueue is difficult because with only a single link it is difficult to “back up”. That is, while you have a pointer to the end sentinel, you do not have an easy way to back up and find the link immediately preceding the sentinel.
Count = 4 frontSentinel = backSentinel =
Sentinel (^5 3 8 3) Sentinel
One solution to this problem is to use a doubly-linked list. In a doubly-linked list, each link maintains two pointers. One link, the forward link, points forward toward the next link in the chain. The other link, the prev link, points backwards towards the previous
Sentinel (^) 3 7 4 2
The root of the problem is that we have fixed the start of the collection at array index position zero. If we simply loosen that requirement, then things become much easier. Now in addition to the data array our collection will maintain two integer data fields; a size (as before) and a starting location.
DataSize = 6 DataStart = 2 Data =
2 4 7 3 9 1
Adding a value to the end is simlar to the ArrayStack. Simply increase the size, and place the new element at the end.
picture
But adding a value to the front is also simple. Simply decrement the starting point by one, then add the new element to the front:
picture
Removing elements undo these operations. As before, if an insertion is performed when the size is equal to the capacity, the array must be doubled in capacity, and the values copied into the new array.
There is just one problem. Nothing prevents the data values from wrapping around from the upper part of the array to the lower:
DataSize = 6 DataStart = 7 Data =
9 1 2 4 7 3
To accommodate index values must be computed carefully. When an index wraps around the end of the array it must be altered to point to the start of the array. This is easily done by subtracting the capacity of the array. That is, suppose we try to index the fifth element in the picture above. We start by adding the index, 5, to the starting location, 7. The resulting sum is 12. But there are only eleven values in the collection. Subtracting 11 from 12 yields 1. This is the index for the value we seek.
In worksheet 20 you will explore the implementation of the dynamic array deque constructed using these ideas. A deque implemented in this fashion is sometimes termed a circular buffer , since the right hand side circles around to begin again on the left.
lastFree
lastFilled
Wikipedia has well written entries for queue, deque, FIFO, as well as on the implementation structures dynamic array, linked list and sentinel node. The NITS Dictionary of Algorithms and Data Structures also has a good explanation.