.Net Programming - Financial independence

The Stack Data Structure in Visual Basic/C#

The stack is similar to the three other collections we’ve seen so far. The major difference resides in its structure. We can compare the Stack to a plate stack in a restaurant. The first plate that will be put in the stack will be the last one to be taken by a client. It’s the same principle for the Generic Stack. Here is an illustration:

First In, Last Out

The gray shapes are the plates, and the orange/blue shapes are the sides of the plate stack. As you can see, when you push a plate on the stack, it will be the first one to pop back out. Frankly, I’ve used the Stack just a few times in some really particular cases but it still came handy in those cases. For example, if I want to fetch an html text, I can store the tags in a stack because the first tag to come out should be the last one I put on the stack just like:

html – head – title and then /title – /head – /html backward.

That’s one thing you can do with a stack, but again, it’s useful to know that it exists for when the time comes you really need it!

Declaration

Here is how you declare a Stack that can contain String values.

Visual Basic

Dim HTMLTags = New Stack(Of String)

C#

Stack<string> htmlTags = new Stack<string>();

Looks like the other collections doesn’t it?! You can also put any type of data in it, it could have been a Stack of Decimal or of Objects too!

Push(T Element)

As with the plate stack, you can push and object using the method Push, in our case it’s going to be an object of type String.

Visual Basic

' Push tags in the stacks, we use a stack because of how HTML tags work!
' The first tag to enter will be the last one to close. 
' <html><head><title></title></head></html>
HTMLTags.Push("html")
HTMLTags.Push("head")
HTMLTags.Push("title")

C#

// Push tags in the stacks, we use a stack because of how HTML tags work!
// The first tag to enter will be the last one to close. 
// <html><head><title></title></head></html>
htmlTags.Push("html");
htmlTags.Push("head");
htmlTags.Push("title");

Peek()

The Peek method takes no argument but returns the next element that will be pop’ed.

Visual Basic

' Peek the top element on the stack.
Console.WriteLine("Peeked Tag: " & HTMLTags.Peek())

C#

// Peek the top element on the stack.
Console.WriteLine("Peeked tag: " + htmlTags.Peek());

Pop()

Removes and returns the top element from the stack. Warning, you must retrieve the element Pop’ed in a variable or use it immediately because it will be removed from the stack as soon as you call the Pop method.

Visual Basic

' Pop the top element.
Dim FirstTag As String = HTMLTags.Pop()
Dim SecondTag As String = HTMLTags.Pop()
Dim ThirdTag As String = HTMLTags.Pop()

' Notice the reverse order than which we've added the elements.
Console.WriteLine("First Tag: " & FirstTag)
Console.WriteLine("Second Tag: " & SecondTag)
Console.WriteLine("Third Tag: " & ThirdTag)

C#

// Pop the elements in order.
string firstTag = htmlTags.Pop();
string secondTag = htmlTags.Pop();
string thirdTag = htmlTags.Pop();

// Notice the reverse order than which we've added the elements.
Console.WriteLine("First Tag: " + firstTag);
Console.WriteLine("Second Tag: " + secondTag);
Console.WriteLine("Third Tag: " + thirdTag);

Result

This window shows what it should give you as a result.

Peek Pop

Again, notice the reverse order from which we’ve put the things in. That’s what we call a FILO or first in, last out type of collection in case you want to sound bright at your next computer science party!

Complete Code

Here is the complete code for this exercise, you should put some breakpoints and play with it!

Visual Basic

Module Program
    Sub Main()
        Dim HTMLTags = New Stack(Of String)

        ' Push tags in the stacks, we use a stack because of how HTML tags work!
        ' The first tag to enter will be the last one to close. 
        ' <html><head><title></title></head></html>
        HTMLTags.Push("html")
        HTMLTags.Push("head")
        HTMLTags.Push("title")

        ' Peek the top element on the stack.
        Console.WriteLine("Peeked Tag: " & HTMLTags.Peek())

        ' Pop the top element.
        Dim FirstTag As String = HTMLTags.Pop()
        Dim SecondTag As String = HTMLTags.Pop()
        Dim ThirdTag As String = HTMLTags.Pop()

        ' Notice the reverse order than which we've added the elements.
        Console.WriteLine("First Tag: " & FirstTag)
        Console.WriteLine("Second Tag: " & SecondTag)
        Console.WriteLine("Third Tag: " & ThirdTag)

        Console.ReadKey()
    End Sub
End Module

C#

using System;
using System.Collections.Generic;

namespace StackCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack<string> htmlTags = new Stack<string>();

            // Push tags in the stacks, we use a stack because of how HTML tags work!
            // The first tag to enter will be the last one to close. 
            // <html><head><title></title></head></html>
            htmlTags.Push("html");
            htmlTags.Push("head");
            htmlTags.Push("title");

            // Peek the top element on the stack.
            Console.WriteLine("Peeked tag: " + htmlTags.Peek());

            // Pop the elements in order.
            string firstTag = htmlTags.Pop();
            string secondTag = htmlTags.Pop();
            string thirdTag = htmlTags.Pop();

            // Notice the reverse order than which we've added the elements.
            Console.WriteLine("First Tag: " + firstTag);
            Console.WriteLine("Second Tag: " + secondTag);
            Console.WriteLine("Third Tag: " + thirdTag);

            Console.ReadKey();
        }
    }
}

What’s Important to Remember

What’s important to remember is that these collections can apply to any type of object, that’s what is so great about them and that’s why you should use them as soon as you need something more complex than a simple array! Don’t forget that these collections (List, Dictionary, Queue and Stack) are not thread safe. Nevertheless, that means they’re still useful in most cases except when you have them accessed by multiple threads, then you might want to look at the Concurrency namespace or use the lock keyword for example.

For additional information, you can look up the Microsoft Website on the Stack Generic.

YouTube

Next article Collections.Generic in Visual Basic/C# - Exercise and Solution
Previous article The Queue Collections.Generic in Visual Basic

Related posts

0 Comments

No Comments Yet!

You can be first to comment this post!

Leave a Comment

Your data will be safe! Your e-mail address will not be published. Also other data will not be shared with third person. Required fields marked as *