Pages

Thursday, May 30, 2013

C#: Stack Implementation with and without Stack class

Stack is a datastructure which operates in Last In First Out manner(LIFO). Which means that the items that are entered last is removed first.

The program below implements stack with and without using Stack class.

Stack Implementation using Stack Class

//Declaring a Stack class
Stack<int> stk = new Stack<int>();


//Method for adding items to Stack
public void AddItems()
{
//Push method add items to Stack
stk.Push(5); // first item
stk.Push(3);
stk.Push(8); //last item
//display Stack
displaystack();
}

//Method for getting items from Stack(gets only, doesn't remove item)
public void GetItems()
{
//Peek method to get last item from Stack
Console.WriteLine("Last item in Stack: "+stk.Peek());
}

//Method to remove items from Stack
public void RemoveItems()
{

//Pop method to remove last item from Stack
stk.Pop();
//display Stack
displaystack();
}

//Method for displaying items in Stack
public void displaystack()
{
Console.WriteLine("The Stack items: ");
//loop through all items in Stack
foreach(int x in stk)
{
Console.WriteLine(x);
}

Output:
The Stack items:
5
3
8
Last item in Stack:
8
The Stack items:
5
3

Stack Implementation without using Stack class

//Declare a list for storing items
List<int> lst = new List<int>();


//Method for adding items to stack(push operation)
public void AddItems()
{
//Use Add() method to add items to Stack
lst.Add(5);
lst.Add(3);
lst.Add(8);

//display Stack
display();
}

//Method to get items from Stack(Peek operation)
public void GetItems()
{
//get item from last index
Console.WriteLine("Last value: "+lst[lst.Count - 1]);
}

//Method for removing last item from Stack(Pop operation)
public void RemoveItems()
{
//Remove last item
lst.RemoveAt(lst.Count - 1);
display();
}

Output:
The Stack Items:
5
3
8
Last value:
8
The Stack Items:
5
3

No comments:

Post a Comment