Stack data structure is a LIFO collection and is a generic type. It exist in C#, and it is defined in namespace:
using System.Collections.Generic;
It can be declared as follows:
Stack<int> stack = new Stack<int>();
and as any stack it has .Push(); .Pop(); and .Peek(); methods. However, when using stack data structure one can face with runtime exception problem if the stack has zero elements. It can be practical to think about making stack data structure with list in C#, as follows:

List<int> stack = new List<int>();
int no_elements = 0;
MessageBox.Show(stack[no_elements – 1].ToString());
stack.RemoveAt(no_elements – 1);

Equivalent of stack operation .Push() is .Add(), equivalent of .Pop() is RemoveAt(no_elements – 1); where no_elements id the variable that we should increase whenever we add element to a list, and decrease whenever we remove element from the list. We can remove arbitrary element, but if we want our list act as stack data structure, we must always remove last element. And also we can present any element in the list, but if we want to emulate .Peek() operation from the stack, we need to read
stack[no_elements – 1].

External links:

Stack data Structure in C# on Dotnetperls
List in C# on on Dotnetperls

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *