Skip to content

Instantly share code, notes, and snippets.

@gdyrrahitis

gdyrrahitis/Stack.cs Secret

Created Nov 7, 2018
Embed
What would you like to do?
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
You can’t perform that action at this time.