Skip to content

Instantly share code, notes, and snippets.

@blackbret94
Last active June 8, 2019 17:31
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 blackbret94/a5959bab8307ce2efc2c89f3137df69a to your computer and use it in GitHub Desktop.
Save blackbret94/a5959bab8307ce2efc2c89f3137df69a to your computer and use it in GitHub Desktop.
Simple data structure that makes it easy to track what members of the collection have been used most recently and which have not been used recently. This is useful for caching and inventory management in video game AI. This class is just a wrapper for a LinkedList with a few helper methods.
using System.Collections;
using System.Collections.Generic;
namespace Util.Collections
{
public class RefreshableStack<T> : IEnumerable<T>
{
private readonly LinkedList<T> _stack;
public IEnumerator<T> GetEnumerator() => _stack.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public int Count => _stack.Count;
public RefreshableStack()
{
_stack = new LinkedList<T>();
}
public bool Contains(T t)
{
return _stack.Contains(t);
}
public void Push(T t)
{
_stack.AddFirst(t);
}
public T Pop()
{
T first = _stack.First.Value;
_stack.RemoveFirst();
return first;
}
public T Peek()
{
return _stack.First.Value;
}
public void Remove(T t)
{
_stack.Remove(t);
}
public T RemoveFromBack()
{
T last = _stack.Last.Value;
_stack.RemoveLast();
return last;
}
public T PeekBack()
{
return _stack.Last.Value;
}
public bool Refresh(T t)
{
if (!Contains(t))
return false;
_stack.Remove(t);
_stack.AddFirst(t);
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment