C# Data Structures – Stack

So a while ago I was in an accounting class learning about inventory management utilizing the First in First out (FIFO) and Last in First out (LIFO).   Since I think about things in ones and zeros I related them to the stack and queue C# data structures.

Stack is a Last in Frist out data structure located in System.Collections.Generic.  Stacks excel when utilized in parsers including complex recursive algorithms.  Stacks have a push (add items to), a pop (remove top item), peek (view top item), and clear (remove all items).

Stacks shine when doing expression evaluations and syntax parsing.

The default capacity for a stack is 10 items.  This can be increased at create time and the stack will automatically resize.  The automatic resize will increase the size based off of twice the initial size.

Here is an example of a stack.

public static void Main(string[] args)
     Stack stack = new Stack();


     Console.WriteLine("Peek the stack, returns {0}", stack.Peek());

Console write line will print out the word the.  Now for fun lets add the following below our code.



var sentence = string.Empty;
while (stack.Count > 0)
    sentence += " " + stack.Peek();

Console.WriteLine("After we pop all the items in the stack this is the sentence we have \n {0}", sentence);

After you run the example the sentence will change to “a quick brown fox jumps over the lazy dog”.

This entry was posted in C# and tagged , . Bookmark the permalink.

One Response to C# Data Structures – Stack

  1. Pingback: C# Data Structures – Queue | Research ~ A ~ holic

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s