using System;
using System.Collections.Generic;
namespace cakeslice
{
///
/// A collection with the fast iteration time of a List and the no-duplicates and fast Remove/Contains time of a HashSet.
///
public class LinkedSet : IEnumerable
{
private LinkedList list;
private Dictionary> dictionary;
public LinkedSet()
{
list = new LinkedList();
dictionary = new Dictionary>();
}
public LinkedSet(IEqualityComparer comparer)
{
list = new LinkedList();
dictionary = new Dictionary>(comparer);
}
///
/// returns true if the item did not already exist in the LinkedSet
///
public bool Add(T t)
{
if (dictionary.ContainsKey(t))
return false;
LinkedListNode node = list.AddLast(t);
dictionary.Add(t, node);
return true;
}
///
/// returns true if the item did previously exist in the LinkedSet
///
public bool Remove(T t)
{
LinkedListNode node;
if (dictionary.TryGetValue(t, out node))
{
dictionary.Remove(t);
list.Remove(node);
return true;
}
else
{
return false;
}
}
public void Clear()
{
list.Clear();
dictionary.Clear();
}
public bool Contains(T t)
=> dictionary.ContainsKey(t);
public int Count
=> list.Count;
public IEnumerator GetEnumerator()
=> list.GetEnumerator();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> list.GetEnumerator();
}
}