-
-
Save gdyrrahitis/295cbc30a14cf2aca906b11042d4f554 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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