IndexableCyclicalLinkedList.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace MonoGame.Extended.Triangulation
  5. {
  6. /// <summary>
  7. /// Implements a LinkedList that is both indexable as well as cyclical. Thus
  8. /// indexing into the list with an out-of-bounds index will automatically cycle
  9. /// around the list to find a valid node.
  10. /// </summary>
  11. /// MIT Licensed: https://github.com/nickgravelyn/Triangulator
  12. class IndexableCyclicalLinkedList<T> : LinkedList<T>
  13. {
  14. /// <summary>
  15. /// Gets the LinkedListNode at a particular index.
  16. /// </summary>
  17. /// <param name="index">The index of the node to retrieve.</param>
  18. /// <returns>The LinkedListNode found at the index given.</returns>
  19. public LinkedListNode<T> this[int index]
  20. {
  21. get
  22. {
  23. //perform the index wrapping
  24. while (index < 0)
  25. index = Count + index;
  26. if (index >= Count)
  27. index %= Count;
  28. //find the proper node
  29. LinkedListNode<T> node = First;
  30. for (int i = 0; i < index; i++)
  31. node = node.Next;
  32. return node;
  33. }
  34. }
  35. /// <summary>
  36. /// Removes the node at a given index.
  37. /// </summary>
  38. /// <param name="index">The index of the node to remove.</param>
  39. public void RemoveAt(int index)
  40. {
  41. Remove(this[index]);
  42. }
  43. /// <summary>
  44. /// Finds the index of a given item.
  45. /// </summary>
  46. /// <param name="item">The item to find.</param>
  47. /// <returns>The index of the item if found; -1 if the item is not found.</returns>
  48. public int IndexOf(T item)
  49. {
  50. for (int i = 0; i < Count; i++)
  51. if (this[i].Value.Equals(item))
  52. return i;
  53. return -1;
  54. }
  55. }
  56. }