Skip to content

Instantly share code, notes, and snippets.

@sirisian
Created March 4, 2020 06:08
Show Gist options
  • Select an option

  • Save sirisian/8a2b2aac920a7e2b47f8ae7bd272348b to your computer and use it in GitHub Desktop.

Select an option

Save sirisian/8a2b2aac920a7e2b47f8ae7bd272348b to your computer and use it in GitHub Desktop.
C# FreeList
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FreeListClass
{
public class FreeList<T>
{
private class FreeListItem<T>
{
public int Previous { get; set; }
public int Next { get; set; }
public T Value { get; set; }
public FreeListItem(int previous, int next)
{
Previous = previous;
Next = next;
}
}
List<FreeListItem<T>> items;
public int allocatedIndexTail = -1;
public int unallocatedIndexHead = 0;
public FreeList(int capacity = 10)
{
items = new List<FreeListItem<T>>();
for (int i = 0; i < capacity - 1; ++i)
{
items.Add(new FreeListItem<T>(i - 1, i + 1));
}
items.Add(new FreeListItem<T>(capacity - 2, -1));
}
public FreeListNode<T> Add(T value)
{
if (items[unallocatedIndexHead].Next == -1)
{
items.Add(new FreeListItem<T>(unallocatedIndexHead, -1));
items[unallocatedIndexHead].Next = items.Count - 1;
}
if (allocatedIndexTail == -1)
{
allocatedIndexTail = unallocatedIndexHead;
unallocatedIndexHead = items[unallocatedIndexHead].Next;
items[allocatedIndexTail].Next = -1;
items[unallocatedIndexHead].Previous = -1;
}
else
{
items[allocatedIndexTail].Next = unallocatedIndexHead;
items[unallocatedIndexHead].Previous = allocatedIndexTail;
allocatedIndexTail = items[allocatedIndexTail].Next;
unallocatedIndexHead = items[unallocatedIndexHead].Next;
items[allocatedIndexTail].Next = -1;
items[unallocatedIndexHead].Previous = -1;
}
return new FreeListNode<T>(this, allocatedIndexTail);
}
public void Remove(int index)
{
FreeListItem<T> value = items[index];
items[unallocatedIndexHead].Previous = index;
if (value.Next != -1)
{
items[value.Next].Previous = value.Previous;
}
if (value.Previous != -1)
{
items[value.Previous].Next = value.Next;
}
if (allocatedIndexTail == index)
{
allocatedIndexTail = value.Previous;
}
value.Next = unallocatedIndexHead;
unallocatedIndexHead = index;
value.Previous = -1;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FreeListClass
{
public class FreeListNode<T>
{
public FreeList<T> FreeList { get; set; }
public int Index { get; set; }
public FreeListNode(FreeList<T> freeList, int index)
{
FreeList = freeList;
Index = index;
}
public void Remove()
{
FreeList.Remove(Index);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FreeListClass
{
class Program
{
static void Main(string[] args)
{
FreeList<int> foo = new FreeList<int>();
foo.Add(0);
foo.Remove(0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment