Introduction: Stack is an abstract data type. It serves as a collection of elements and follow LIFO(last in first out) pattern. So every new added item goes on the top of the stack, and only top item can be removed first.
It has main 2 operations
push: This operation adds an element to
the collection at the top
pop: It removes the most recently added
element that was not yet removed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stack
{
public interface
IStack<T>
{
void
Push(T element);
T
Pop();
void
Print();
}
public class
Stack<T> : IStack<T>
{
private
T[] _items = new T[10] ;
private
int _top = -1;
public
void Push(T element)
{
if (_top < 9)
{
_items[++_top] = element;
}
else
{
throw new Exception("Stack is full. Item can't be
added.");
}
}
public
void Print()
{
for (int i = _top; i > -1; i--)
{
Console.WriteLine("index:{0} item:{1}",i,_items[i]);
}
}
public
T Pop()
{
if (_top == -1)
{
throw new Exception("Stack is empty.");
}
return _items[_top--];
}
}
public class Program
{
public
static void Main(string[] args)
{
var stack = new Stack<int>();
stack.Push(110);
stack.Push(101);
stack.Push(111);
stack.Print();
var item = stack.Pop();
Console.WriteLine("Poped item :: {0}",item);
stack.Print();
stack.Push(200);
stack.Print();
Console.ReadKey();
}
}
}
Complexity Analysis
push,pop: O(1) &
search: O(n)
No comments:
Post a Comment