Working with Queues and Stacks

WEBINAR:On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

Introduction

Apart from Hashtables, queues and stacks are probably the most common Collection classes. With this article I will explain the ins and outs of queues and stacks.

Again with the Collections?

Yes. After you have seen how versatile the Collections Namespace is, you'll never again cringe with fear when you encounter it, and you will - many times!

What is a Queue?

When you go to a bank or a grocery store you have to stand in a queue for service. The first person in the queue is the first person helped. The last person in the queue is the last person helped. Agreed? Now, the Queue class works the same way. It is what is called a FIFO ( First in, First out ) list.

As this MSDN article mentions: Queues are useful for storing messages in the order they were received for sequential processing. This class implements a queue as a circular array. Objects stored in a Queue are inserted at one end and removed from the other.

What is a Stack?

A Stack is the opposite of a Queue. Where a Queue is a FIFO list, a Stack represents a LIFO (Last in, First out ) list. This analogy is the same as a stack of books. The first book you place on your desk, will remain at the bottom, whereas the last book that you have placed on the stack, will most likely be used / discarded first.

Sample Programs

If you still find these two classes hard to understand, I have worked out samples for you. These samples are in VB.NET and C#. You are welcome following the next few steps in creating your project in your specific language ( VB.NET or C# ).

This is where it gets interesting! Once we have our lists set up, there are numerous ways in which we can access the items inside the lists. With the Queue object we can use its Dequeue method. This will in effect release the first object added to the list, for example.

VB.NET :

Console.WriteLine("(Dequeue) {0}", qMyQueue.Dequeue())

C# :

Console.WriteLine("(Dequeue) {0}", qMyQueue.Dequeue())

Would remove first from the list, next time it is called, second will be removed and so on.

With the Stack object we would need to use the Pop method.

VB.NET :

Console.WriteLine("(Pop){0}", sMyStack.Pop())

C# :

Console.WriteLine("(Pop){0}", sMyStack.Pop());

The above code for the Stack object would remove the last item in the list, so in our example, third, then second, then first.

We could also make use of a loop to iterate through the Queue and Stack completely:

The IEnumerator Interface

I decided to mention this Interface here as I am trying to teach you how to use the Collection classes properly. The IEnumerator Interface provides a way for us to enumerate, or iterate, or simply, loop through the certain Collection class. It exposes methods such as MoveNext, which moves to the next item in the list, and Current, which shows the current item in the list. We need an IEnumerable Interface object so that it can expose (identify) the enumerator, which supports a simple iteration over a non-generic collection.

Let us add this functionality. Add the following procedure to your code.

VB.NET :

Public Sub DisplayValues(ByVal MyQueueCollection As IEnumerable, ByVal MyStackCollection As IEnumerable)
Dim MyQueueEnumerator As IEnumerator = MyQueueCollection.GetEnumerator() 'Get list(s) to iterate through
Dim MyStackEnumerator As IEnumerator = MyStackCollection.GetEnumerator()
While MyQueueEnumerator.MoveNext() 'Move to next item
ListBox1.Items.Add(MyQueueEnumerator.Current.ToString())
End While
While MyStackEnumerator.MoveNext()
ListBox2.Items.Add(MyStackEnumerator.Current.ToString()) 'Display current item
End While
End Sub

Related Articles

Downloads

Comments

Cringes

Posted by Hannes du Preez
on 11/26/2012 03:13am

Hi Dominic.
Thanks a lot for reading and your honest feedback!
I am involved with many online forums as well as give programming classes to students. I also work with many a professional programmers who always try to circumvent the collections namespaces - because they are scared of it. I can't tell you why they seem to be scared of it - perhaps not having the correct fundamentals of programming? Beats me. That is why I try to teach my students about things like this

A question about this article

Posted by Dominic
on 09/25/2012 05:06am

I'm curious to know who "cringe[s] with fear when [they] encounter" the Collections namespace? It's widely used and its members are basic data structures that are seen in any entry level CS classes. I'd like to understand what are the motivations to do such an article series? Did you have requests for it? Did you have visitor feedback saying your previous articles were too advanced? I'm really curious about this...
Thanks

I cringe

Posted by Dam
on 10/23/2012 09:04am

I didn't know the collections namespace existed; I've been programming in .NET for 10 years. This article has opened my eyes.

Top White Papers and Webcasts

Many enterprises are working with an IT architecture that's evolved over time. As business needs evolve, IT must decide whether to modernize incrementally, or all at once. Each approach has its benefits and drawbacks. Identity Management is key to modernizing IT; it plays a crucial role in migrating to cloud apps like Office 365 or HR information systems, building web and mobile apps, and opening developer access to business systems. Read how Okta's modern approach to identity management helps business lower …

The software-defined data center (SDDC) and new trends in cloud and virtualization bring increased agility, automation, and intelligent services and management to all areas of the data center. Businesses can now more easily manage the entire lifecycle of their applications and services via the SDDC. This Aberdeen analyst report examines how a strong foundation in both the cloud and internal data centers is empowering organizations to fully leverage their IT infrastructure and is also preparing them to be able …