C# - ADT - Implement Stack using List in C#
C# - ADT - Implement Stack using List in C#
CODE
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
//initialise the Stack class
Stack stack = new Stack();
//Push the elements to the Stack
stack.Push(10);
stack.Push(20);
stack.Push(30);
stack.Push(40);
//Display the Stack
stack.Print();
int poppedValue = stack.Pop();
Console.WriteLine("Popped Value: {0}", poppedValue);
//Display the Stack
stack.Print();
stack.Push(100);
stack.Print();
//OUTPUT
//Stack follows:40 30 20 10
//Popped Value: 40
//Stack follows:30 20 10
//Stack follows:100 30 20 10
Console.ReadKey();
}
}
class Stack
{
private int top = -1;
private List<int> items = new List<int>();
//Returns true if the Stack is empty
public bool IsEmpty()
{
if (top == -1)
return true;
else
return false;
}
//insert the data to the top of the stack
//the top variable is incremented before inserting the element
public bool Push(int data)
{
top++;
items.Add(data);
return true;
}
//removes and returns the topmost element from the stack
//the top variable is decremented by 1
public int Pop()
{
if (IsEmpty())
{
Console.WriteLine("The Stack is empty.");
return 0;
}
else
{
int value = items[top];
items.RemoveAt(top);
top--;
return value;
}
}
//print the topmost element in the stack
public void Peek()
{
if (IsEmpty())
Console.WriteLine("The Stack is empty.");
else
Console.WriteLine("The topmost element of Stack is : {0}", items[top]);
}
//print all the elements in the stack.
public void Print()
{
if (IsEmpty())
Console.WriteLine("The Stack is empty.");
else
{
Console.Write("Stack follows:");
for (int i = top; i >= 0; i--)
{
Console.Write(items[i] + " ");
}
Console.WriteLine();
}
}
}
Comments
Post a Comment