C# - Implement Stack using array in C#
The program to implement Stack using array in C#
CODE
using System;
class Program
{
static void Main(string[] args)
{
//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();
Console.ReadKey();
}
}
class Stack
{
//The top variable points to the top element in the stack
static readonly int MAX = 1000;
int top = -1;
int[] stack = new int[MAX];
//Returns true if the Stack is empty
public bool IsEmpty()
{
if (top == -1)
return true;
else
return false;
}
//Returns true if the Stack is full
public bool IsFull()
{
if (top == MAX-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)
{
if (IsFull())
{
Console.WriteLine("The Stack is full.");
return false;
}
else
{
top++;
stack[top] = 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 = stack[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}", stack[top]);
}
//print all the elements in the stack.
public void Print()
{
if (IsEmpty())
Console.WriteLine("The Stack is empty.");
else
{
Console.WriteLine("Stack follows:");
for (int i = top; i >= 0; i--)
{
Console.Write(stack[i] + " ");
}
Console.WriteLine();
}
}
}
INPUT & OUTPUT
Comments
Post a Comment