|
| 1 | +using System.Collections.Generic; |
| 2 | + |
| 3 | +namespace DataStructures.UnrolledList |
| 4 | +{ |
| 5 | + /// <summary> |
| 6 | + /// Unrolled linked list is a linked list of small arrays, |
| 7 | + /// all of the same size where each is so small that the insertion |
| 8 | + /// or deletion is fast and quick, but large enough to fill the cache line. |
| 9 | + /// </summary> |
| 10 | + public class UnrolledLinkedList |
| 11 | + { |
| 12 | + private readonly int sizeNode; |
| 13 | + |
| 14 | + private UnrolledLinkedListNode start = null!; |
| 15 | + private UnrolledLinkedListNode end = null!; |
| 16 | + |
| 17 | + /// <summary> |
| 18 | + /// Initializes a new instance of the <see cref="UnrolledLinkedList"/> class. |
| 19 | + /// Create a unrolled list with start chunk size. |
| 20 | + /// </summary> |
| 21 | + /// <param name="chunkSize">The size of signe chunk.</param> |
| 22 | + public UnrolledLinkedList(int chunkSize) |
| 23 | + { |
| 24 | + sizeNode = chunkSize + 1; |
| 25 | + } |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// Add value to list [O(n)]. |
| 29 | + /// </summary> |
| 30 | + /// <param name="value">The entered value.</param> |
| 31 | + public void Insert(int value) |
| 32 | + { |
| 33 | + if (start == null) |
| 34 | + { |
| 35 | + start = new UnrolledLinkedListNode(sizeNode); |
| 36 | + start.Set(0, value); |
| 37 | + |
| 38 | + end = start; |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + if (end.Count + 1 < sizeNode) |
| 43 | + { |
| 44 | + end.Set(end.Count, value); |
| 45 | + } |
| 46 | + else |
| 47 | + { |
| 48 | + var pointer = new UnrolledLinkedListNode(sizeNode); |
| 49 | + var j = 0; |
| 50 | + for (var pos = end.Count / 2 + 1; pos < end.Count; pos++) |
| 51 | + { |
| 52 | + pointer.Set(j++, end.Get(pos)); |
| 53 | + } |
| 54 | + |
| 55 | + pointer.Set(j++, value); |
| 56 | + pointer.Count = j; |
| 57 | + |
| 58 | + end.Count = end.Count / 2 + 1; |
| 59 | + end.Next = pointer; |
| 60 | + end = pointer; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + /// <summary> |
| 65 | + /// Help method. Get all list inside to check the state. |
| 66 | + /// </summary> |
| 67 | + /// <returns>Items from all nodes.</returns> |
| 68 | + public IEnumerable<int> GetRolledItems() |
| 69 | + { |
| 70 | + UnrolledLinkedListNode pointer = start; |
| 71 | + List<int> result = new(); |
| 72 | + |
| 73 | + while (pointer != null) |
| 74 | + { |
| 75 | + for (var i = 0; i < pointer.Count; i++) |
| 76 | + { |
| 77 | + result.Add(pointer.Get(i)); |
| 78 | + } |
| 79 | + |
| 80 | + pointer = pointer.Next; |
| 81 | + } |
| 82 | + |
| 83 | + return result; |
| 84 | + } |
| 85 | + } |
| 86 | +} |
0 commit comments