-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCountBasedSelfOrganizingList.cs
More file actions
88 lines (73 loc) · 2.42 KB
/
Copy pathCountBasedSelfOrganizingList.cs
File metadata and controls
88 lines (73 loc) · 2.42 KB
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
86
87
88
namespace AlgorithmsAndDataStructures.DataStructures.SelfOrganizingList;
public class CountBasedSelfOrganizingList<T>
{
private CountBaseSelfOganizedListNode<T> tail;
public CountBaseSelfOganizedListNode<T> Head { get; private set; }
public void Add(T value)
{
if (Head is null)
{
Head = new CountBaseSelfOganizedListNode<T> { Value = value };
tail = Head;
return;
}
tail.Next = new CountBaseSelfOganizedListNode<T> { Value = value };
tail = tail.Next;
}
public CountBaseSelfOganizedListNode<T> Get(T value)
{
if (Head is null) return null;
#pragma warning disable HAA0601 // Value type to reference type conversion causing boxing allocation
if (Head.Value.Equals(value))
{
#pragma warning restore HAA0601 // Value type to reference type conversion causing boxing allocation
Head.Count += 1;
return Head;
}
var current = Head.Next;
var previous = Head;
while (current != null)
{
#pragma warning disable HAA0601 // Value type to reference type conversion causing boxing allocation
if (current.Value.Equals(value))
#pragma warning restore HAA0601 // Value type to reference type conversion causing boxing allocation
{
previous.Next = current.Next;
current.Next = Head;
Head = current;
Head.Count += 1;
Sink();
return current;
}
previous = current;
current = current.Next;
}
return null;
}
private void Sink()
{
if (Head.Next is null) return;
if (Head.Count < Head.Next.Count)
{
var next = Head.Next;
Head.Next = next.Next;
next.Next = Head;
Head = next;
}
var current = Head.Next;
var previous = Head;
while (current?.Next != null)
{
if (current.Count < current.Next.Count) Swap(previous, current, current.Next);
current = current.Next;
}
}
private static void Swap(CountBaseSelfOganizedListNode<T> previous, CountBaseSelfOganizedListNode<T> current,
CountBaseSelfOganizedListNode<T> next)
{
if (next is null) return;
previous.Next = next;
current.Next = next.Next;
next.Next = current;
}
}