C# program to implement stack
Here's a C# program that implements a stack data structure:
using System;
public class Stack
{
private T[] items;
private int top;
public Stack(int capacity)
{
items = new T[capacity];
top = -1;
}
public bool IsEmpty()
{
return top == -1;
}
public bool IsFull()
{
return top == items.Length - 1;
}
public void Push(T item)
{
if (IsFull())
{
throw new InvalidOperationException("Stack is full");
}
items[++top] = item;
}
public T Pop()
{
if (IsEmpty())
{
throw new InvalidOperationException("Stack is empty");
}
return items[top--];
}
public T Peek()
{
if (IsEmpty())
{
throw new InvalidOperationException("Stack is empty");
}
return items[top];
}
}
public class Program
{
public static void Main()
{
Stack stack = new Stack(5);
stack.Push(1);
stack.Push(2);
stack.Push(3);
stack.Push(4);
stack.Push(5);
Console.WriteLine("Stack peek: " + stack.Peek());
while (!stack.IsEmpty())
{
Console.WriteLine("Popped: " + stack.Pop());
}
}
}
In this program, the 'Stack' class is a generic class that represents a stack. It uses an array to store the stack items, and the 'top' variable keeps track of the index of the top item in the stack.
The stack has the following methods:
-
'IsEmpty()': Checks if the stack is empty.
-
'IsFull()': Checks if the stack is full.
-
'Push(T item)': Pushes an item onto the stack.
-
'Pop()': Pops and returns the top item from the stack.
-
'Peek()': Returns the top item from the stack without removing it.
In the Main method, we create a Stack object with a capacity of 5. We then push some integers onto the stack and print the top item using Peek(). Finally, we pop all the items from the stack and print them.