Advertisement
phi2dao

ChainedList

Oct 4th, 2024
9
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. public class ChainedList<T>
  2. {
  3. internal readonly RecycleList<Link> _list = [];
  4. internal readonly record struct Link(T Value, int Next);
  5. }
  6.  
  7. public sealed class Chain<T>
  8. {
  9. public ChainedList<T> List { get; }
  10. public T Current
  11. {
  12. get => List[_head].Value;
  13. set => List[_head] = new(value, List[_head].Next);
  14. }
  15.  
  16. internal Chain(ChainedList<T> list, int index)
  17. {
  18. List = list;
  19. _prev = -1;
  20. _head = index;
  21. }
  22.  
  23. public bool MoveNext()
  24. {
  25. int next = List[_head].Next;
  26. _prev = _head;
  27. return (_head = next) > 0;
  28. }
  29.  
  30. public void AddBefore(T value)
  31. {
  32. int index = List.NextIndex();
  33. List[_prev] = new(List[_prev].Value, index);
  34. List[index] = new(value, _head);
  35. }
  36.  
  37. public void AddAfter(T value)
  38. {
  39. int index = NextIndex();
  40. List[index] = new(value, List[_head].Next);
  41. List[_head] = new(List[_head].Value, index);
  42. }
  43.  
  44. public bool Remove()
  45. {
  46. int next = List[_head].Next;
  47. List[_prev] = new(List[_prev].Value, next);
  48. List.Recycle(_head, default);
  49. return (_head = next) > 0;
  50. }
  51.  
  52. private int _prev;
  53. private int _head;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement