Skip to content

Instantly share code, notes, and snippets.

@gdyrrahitis
Created November 7, 2018 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdyrrahitis/295cbc30a14cf2aca906b11042d4f554 to your computer and use it in GitHub Desktop.
Save gdyrrahitis/295cbc30a14cf2aca906b11042d4f554 to your computer and use it in GitHub Desktop.
public class Stack<T>
{
private readonly T[] _stack;
private readonly int _size;
private int _topMostItemIndex = -1;
public Stack(int size = 16)
{
_size = size;
_stack = new T[size];
}
public bool IsEmpty => _topMostItemIndex == -1;
private bool IsFull => _size == _topMostItemIndex + 1;
public void Push(T value)
{
if (IsFull)
{
throw new Exception("Stack is full");
}
_stack[++_topMostItemIndex] = value;
}
public T Pop()
{
if (IsEmpty)
{
throw new Exception("Stack is empty");
}
return _stack[_topMostItemIndex--];
}
public T Peek()
{
if (IsEmpty)
{
throw new Exception("Stack is empty");
}
return _stack[_topMostItemIndex];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment