quantum-space-buddies/QSB/Utility/ListStack.cs

82 lines
1.5 KiB
C#
Raw Normal View History

2023-02-10 12:01:31 +00:00
using System;
using System.Collections;
using System.Collections.Generic;
namespace QSB.Utility;
public class ListStack<T> : IEnumerable<T>
{
2023-05-07 17:23:40 +00:00
private List<T> _items = new();
public int Count => _items.Count;
2023-05-07 23:33:04 +00:00
private readonly bool _removeDuplicates;
2023-05-07 17:23:40 +00:00
public ListStack(bool removeDuplicates)
2023-05-07 17:23:40 +00:00
{
2023-05-07 23:33:04 +00:00
_removeDuplicates = removeDuplicates;
2023-05-07 17:23:40 +00:00
}
2023-02-10 12:01:31 +00:00
public void Clear()
=> _items.Clear();
public void Push(T item)
{
2023-05-07 23:33:04 +00:00
if (_removeDuplicates && _items.Contains(item))
2023-02-10 12:01:31 +00:00
{
RemoveAll(x => EqualityComparer<T>.Default.Equals(x, item));
}
_items.Add(item);
}
public T Pop()
{
if (_items.Count > 0)
{
var temp = _items[_items.Count - 1];
_items.RemoveAt(_items.Count - 1);
return temp;
}
return default;
}
2023-05-07 17:23:40 +00:00
public T RemoveFirstElementAndShift()
{
if (_items.Count == 0)
{
return default;
}
var firstElement = _items[0];
if (_items.Count == 0)
{
return firstElement;
}
// shift list left
// allocates blehhh who cares
2023-05-07 17:23:40 +00:00
_items = _items.GetRange(1, _items.Count - 1);
return firstElement;
}
2023-02-10 12:01:31 +00:00
public T Peek() => _items.Count > 0
? _items[_items.Count - 1]
: default;
public void RemoveAt(int index)
=> _items.RemoveAt(index);
public bool Remove(T item)
=> _items.Remove(item);
public int RemoveAll(Predicate<T> match)
=> _items.RemoveAll(match);
IEnumerator<T> IEnumerable<T>.GetEnumerator() => ((IEnumerable<T>)_items).GetEnumerator();
public IEnumerator GetEnumerator() => ((IEnumerable<T>)_items).GetEnumerator();
}