Created
March 26, 2021 06:40
-
-
Save ElysiumWhale/01e6145b25329c77378876d870e3994b to your computer and use it in GitHub Desktop.
Stack-like working collection class which drops bottom value while adding new value if store is full
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 LimitedSizeStack<T> | |
{ | |
private int _count; | |
private int _index; | |
private int _limit; | |
private T[] _data; | |
public int Count => _count; | |
public int Limit => _limit; | |
public LimitedSizeStack(int limit) | |
{ | |
#warning Zero size stack danger! | |
if (limit <= 0) _limit = -1; | |
// or there can be | |
// throw new ArgumentException("Size of stack can't be 0 or less"); | |
else | |
{ | |
_count = 0; | |
_limit = limit; | |
_data = new T[limit]; | |
_index = 0; | |
} | |
} | |
private void IncreaseIndex() => _index = (_index == _limit - 1) ? 0 : _index + 1; | |
public void Push(T item) | |
{ | |
if (_limit == -1) return; | |
if (_count != _limit) | |
{ | |
_data[_index] = item; | |
_count++; | |
IncreaseIndex(); | |
} | |
else if (_count == _limit) | |
{ | |
_data[_index] = item; | |
IncreaseIndex(); | |
} | |
} | |
public T Pop() | |
{ | |
if (_limit == -1) return default; | |
if (_count == 0) return default; | |
_index = (_index == 0) ? (_limit - 1) : _index - 1; | |
T res = _data[_index]; | |
_data[_index] = default; | |
_count--; | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment