-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
SkipList.cs
372 lines (308 loc) · 10.3 KB
/
SkipList.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/***
* The Skip-List data structure implementation.
*
* Uses the custom class SkipListNode<T>.
*
* Note: A more memory efficient implementation would use structs, but this is the simplest implementation possible.
*/
using System;
using System.Collections.Generic;
using DataStructures.Common;
namespace DataStructures.Lists
{
/// <summary>
/// THE SKIP-LIST DATA STRUCTURE
/// </summary>
public class SkipList<T> : ICollection<T>, IEnumerable<T> where T : IComparable<T>
{
private int _count { get; set; }
private int _currentMaxLevel { get; set; }
private Random _randomizer { get; set; }
// The skip-list root node
private SkipListNode<T> _firstNode { get; set; }
// Readonly values
private readonly int MaxLevel = 32;
private readonly double Probability = 0.5;
/// <summary>
/// Private helper. Used in Add method.
/// </summary>
/// <returns></returns>
private int _getNextLevel()
{
int lvl = 0;
while (_randomizer.NextDouble() < Probability && lvl <= _currentMaxLevel && lvl < MaxLevel)
++lvl;
return lvl;
}
/// <summary>
/// CONSTRUCTOR
/// </summary>
public SkipList()
{
_count = 0;
_currentMaxLevel = 1;
_randomizer = new Random();
_firstNode = new SkipListNode<T>(default(T), MaxLevel);
for (int i = 0; i < MaxLevel; ++i)
_firstNode.Forwards[i] = _firstNode;
}
/// <summary>
/// Getter accessor for the first node
/// </summary>
public SkipListNode<T> Root
{
get { return _firstNode; }
}
/// <summary>
/// Checks if list is empty or not
/// </summary>
public bool IsEmpty
{
get { return Count == 0; }
}
/// <summary>
/// Return count of elements
/// </summary>
public int Count
{
get { return _count; }
}
/// <summary>
/// Return current max-node level
/// </summary>
public int Level
{
get { return _currentMaxLevel; }
}
/// <summary>
/// Access elements by index
/// </summary>
public T this[int index]
{
get
{
// TODO:
throw new NotImplementedException();
}
}
/// <summary>
/// Adds item to the list
/// </summary>
public void Add(T item)
{
var current = _firstNode;
var toBeUpdated = new SkipListNode<T>[MaxLevel];
for (int i = _currentMaxLevel - 1; i >= 0; --i)
{
while (current.Forwards[i] != _firstNode && current.Forwards[i].Value.IsLessThan(item))
current = current.Forwards[i];
toBeUpdated[i] = current;
}
current = current.Forwards[0];
// Get the next node level, and update list level if required.
int lvl = _getNextLevel();
if (lvl > _currentMaxLevel)
{
for (int i = _currentMaxLevel; i < lvl; ++i)
toBeUpdated[i] = _firstNode;
_currentMaxLevel = lvl;
}
// New node
var newNode = new SkipListNode<T>(item, lvl);
// Insert the new node into the skip list
for (int i = 0; i < lvl; ++i)
{
newNode.Forwards[i] = toBeUpdated[i].Forwards[i];
toBeUpdated[i].Forwards[i] = newNode;
}
// Increment the count
++_count;
}
/// <summary>
/// Remove element from the list.
/// </summary>
public bool Remove(T item)
{
T deleted;
return Remove(item, out deleted);
}
/// <summary>
/// Remove an element from list and then return it
/// </summary>
public bool Remove(T item, out T deleted)
{
// Find the node in each of the levels
var current = _firstNode;
var toBeUpdated = new SkipListNode<T>[MaxLevel];
// Walk after all the nodes that have values less than the node we are looking for.
// Mark all nodes as toBeUpdated.
for (int i = _currentMaxLevel - 1; i >= 0; --i)
{
while (current.Forwards[i] != _firstNode && current.Forwards[i].Value.IsLessThan(item))
current = current.Forwards[i];
toBeUpdated[i] = current;
}
current = current.Forwards[0];
// Return default value of T if the item was not found
if (current.Value.IsEqualTo(item) == false)
{
deleted = default(T);
return false;
}
// We know that the node is in the list.
// Unlink it from the levels where it exists.
for (int i = 0; i < _currentMaxLevel; ++i)
if (toBeUpdated[i].Forwards[i] == current)
toBeUpdated[i].Forwards[i] = current.Forwards[i];
// Decrement the count
--_count;
// Check to see if we've deleted the highest-level node
// Decrement level
while (_currentMaxLevel > 1 && _firstNode.Forwards[_currentMaxLevel - 1] == _firstNode)
--_currentMaxLevel;
// Assign the deleted output parameter to the node.Value
deleted = current.Value;
return true;
}
/// <summary>
/// Checks if an item is in the list
/// </summary>
public bool Contains(T item)
{
T itemOut;
return Find(item, out itemOut);
}
/// <summary>
/// Look for an element and return it if found
/// </summary>
public bool Find(T item, out T result)
{
var current = _firstNode;
// Walk after all the nodes that have values less than the node we are looking for
for (int i = _currentMaxLevel - 1; i >= 0; --i)
while (current.Forwards[i] != _firstNode && current.Forwards[i].Value.IsLessThan(item))
current = current.Forwards[i];
current = current.Forwards[0];
// Return true if we found the element; false otherwise
if (current.Value.IsEqualTo(item))
{
result = current.Value;
return true;
}
result = default(T);
return false;
}
/// <summary>
/// Deletes the min element if the list is empty; otherwise throws exception
/// </summary>
public T DeleteMin()
{
T min;
if (!TryDeleteMin(out min))
{
throw new InvalidOperationException("SkipList is empty.");
}
return min;
}
/// <summary>
/// Tries to delete the min element, returns false if list is empty
/// </summary>
public bool TryDeleteMin(out T result)
{
if (IsEmpty)
{
result = default(T);
return false;
}
return Remove(_firstNode.Forwards[0].Value, out result);
}
/// <summary>
/// Returns the first element if the list is not empty; otherwise throw an exception
/// </summary>
public T Peek()
{
T peek;
if (!TryPeek(out peek))
{
throw new InvalidOperationException("SkipList is empty.");
}
return peek;
}
/// <summary>
/// Tries to return the first element, if the list is empty it returns false
/// </summary>
public bool TryPeek(out T result)
{
if (IsEmpty)
{
result = default(T);
return false;
}
result = _firstNode.Forwards[0].Value;
return true;
}
#region IEnumerable<T> Implementation
/// <summary>
/// IEnumerable method implementation
/// </summary>
public IEnumerator<T> GetEnumerator()
{
var node = _firstNode;
while (node.Forwards[0] != null && node.Forwards[0] != _firstNode)
{
node = node.Forwards[0];
yield return node.Value;
}
}
/// <summary>
/// IEnumerable method implementation
/// </summary>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion IEnumerable<T> Implementation
#region ICollection<T> Implementation
/// <summary>
/// Checks whether this collection is readonly
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Copy this list to an array
/// </summary>
public void CopyTo(T[] array, int arrayIndex)
{
// Validate the array and arrayIndex
if (array == null)
throw new ArgumentNullException();
if (array.Length == 0 || arrayIndex >= array.Length || arrayIndex < 0)
throw new IndexOutOfRangeException();
// Get enumerator
var enumarator = this.GetEnumerator();
// Copy elements as long as there is any in the list and as long as the index is within the valid range
for (int i = arrayIndex; i < array.Length; ++i)
{
if (enumarator.MoveNext())
array[i] = enumarator.Current;
else
break;
}
}
/// <summary>
/// Clears this instance
/// </summary>
public void Clear()
{
_count = 0;
_currentMaxLevel = 1;
_randomizer = new Random();
_firstNode = new SkipListNode<T>(default(T), MaxLevel);
for (int i = 0; i < MaxLevel; ++i)
_firstNode.Forwards[i] = _firstNode;
}
#endregion
}
}