Skip to content

Commit

Permalink
Fix aalhour#140 Program crashes upon search for null in a SkipList<st…
Browse files Browse the repository at this point in the history
…ring>
  • Loading branch information
Gutsonok committed Aug 8, 2020
1 parent 377a8d1 commit 321e838
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
20 changes: 19 additions & 1 deletion DataStructures/Lists/SkipList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -208,12 +208,31 @@ public bool Contains(T item)
/// </summary>
public bool Find(T item, out T result)
{
result = default(T);

var current = _firstNode;

// If find null element then check first element after first node
if (item == null)
{
current = current.Forwards[0];
return current != null && current.Value == null;
}

// Skip null element (in first postion) if contain
if (!IsEmpty && current.Forwards[0].Value == null)
{
current = current.Forwards[0];
}

// 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] != null && current.Forwards[i].Value.IsLessThan(item))
{
current = current.Forwards[i];
}
}

current = current.Forwards[0];

Expand All @@ -224,7 +243,6 @@ public bool Find(T item, out T result)
return true;
}

result = default(T);
return false;
}

Expand Down
27 changes: 25 additions & 2 deletions UnitTest/DataStructuresTests/SkipListTest.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Runtime.InteropServices.ComTypes;
using DataStructures.Lists;
using DataStructures.Lists;
using Xunit;

namespace UnitTest.DataStructuresTests
Expand All @@ -16,6 +15,17 @@ public static void Initialization_ListIsEmpty()
Assert.DoesNotContain(0, skipList);
}

[Fact]
public static void InitializationWithReferencyTypeAsGeneric_ListIsEmpty()
{
var skipList = new SkipList<string>();

Assert.True(skipList.Count == 0);
Assert.True(skipList.IsEmpty);
Assert.DoesNotContain(null, skipList);
Assert.DoesNotContain(string.Empty, skipList);
}

[Fact]
public static void Add_NullElement_ListContainNullElement()
{
Expand All @@ -27,6 +37,19 @@ public static void Add_NullElement_ListContainNullElement()
Assert.Contains(null, skipList);
}

[Fact]
public static void Add_NullElementAfterNonNull_ListContainNullElement()
{
var skipList = new SkipList<string>();

skipList.Add("1");
skipList.Add(null);

Assert.True(skipList.Count == 2);
Assert.Contains(null, skipList);
Assert.Contains("1", skipList);
}

[Theory]
[InlineData(10)]
[InlineData(-10)]
Expand Down

0 comments on commit 321e838

Please sign in to comment.