Queues

A queue also deals with temporary data elegantly, and is like a stack in that it is an array with restrictions. The difference lies in what order we want to process our data, and this depends on the particular application we are working on.

You can think of a queue as a line of people at the movie theater. The first one on the line is the first one to leave the line and enter the theater. With queues, the first item added to the queue is the first item to be removed. That’s why computer scientists use the acronym “FIFO” when it comes to queues: First In, First Out.

Like stacks, queues are arrays with three restrictions (it’s just a different set of restrictions):

  • Data can only be inserted at the end of a queue. (This is identical behavior as the stack.)

  • Data can only be read from the front of a queue. (This is the opposite of behavior of the stack.)

  • Data can only be removed from the front of a queue. (This, too, is the opposite behavior of the stack.)

Let’s see a queue in action, beginning with an empty queue.

First, we insert a 5: (While inserting into a stack is called pushing, inserting into a queue doesn’t have a standardized name. Various references call it putting, adding, or enqueuing.)

images/chapter9/stacks_and_queues_Part20.png

Next, we insert a 9:

images/chapter9/stacks_and_queues_Part21.png

Next, we insert a 100:

images/chapter9/stacks_and_queues_Part22.png

As of now, the queue has functioned just like a stack. However, removing data happens in the reverse, as we remove data from the front of the queue.

If we want to remove data, we must start with the 5, since it’s at the front of the queue:

images/chapter9/stacks_and_queues_Part23.png

Next, we remove the 9:

images/chapter9/stacks_and_queues_Part24.png

Our queue now only contains one element, the 100.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset