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