Skip to content

Instantly share code, notes, and snippets.

@netcore-jroger
Last active July 6, 2017 02:27
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 netcore-jroger/9b09245aad10a71d3908 to your computer and use it in GitHub Desktop.
Save netcore-jroger/9b09245aad10a71d3908 to your computer and use it in GitHub Desktop.
public interface ILinkedSetElement<T> where T : class, ILinkedSetElement<T>
{
T Next { get; set; }
}
public class LinkedSet<T> where T : class, ILinkedSetElement<T>
{
private T _top;
private T _bottom;
public void Add(T ele)
{
if (ele.Next != null)
{
T tempElement = ele.Next;
while (true)
{
if (tempElement.Next == null)
{
break;
}
tempElement = tempElement.Next;
}
tempElement.Next = this._top;
this._top = ele;
}
else
{
Debug.Assert(ele.Next == null, "It's already in a set!");
ele.Next = this._top;
this._top = ele;
}
if (this._bottom == null)
{
this._bottom = this._top;
}
}
public T RemoveOne()
{
var top = this._top;
this._top = this._top.Next;
if (this._top == null)
{
this._bottom = null;
}
top.Next = null;
return top;
}
public bool IsEmpty()
{
return this._top == null;
}
public bool Contains(T ele)
{
return ele.Next != null || ele == this._bottom;
}
public static List<LinkedSet<T>> Create(int capacity)
{
if (capacity <= 0) throw new ArgumentException("the capacity parameter must be greate than zero.");
var sets = new LinkedSet<T>();
var instances = new List<LinkedSet<T>>(capacity);
int index;
for (index = 0; index < capacity; index++)
{
instances.Add(sets);
}
return instances;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment