Skip to content

Commit 768dc4b

Browse files
committed
Fix SkipList remove operation
1 parent e59568b commit 768dc4b

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

src/main/java/com/thealgorithms/datastructures/lists/SkipList.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,12 @@ public E get(int index) {
100100
return current.value;
101101
}
102102

103+
/*
104+
java.lang.NullPointerException: Cannot invoke
105+
"com.thealgorithms.datastructures.lists.SkipList$Node.setPrevious(int, com.thealgorithms.datastructures.lists.SkipList$Node)"
106+
because the return value of "com.thealgorithms.datastructures.lists.SkipList$Node.next(int)" is null
107+
at com.thealgorithms.datastructures.lists.SkipListTest.remove(SkipListTest.java:50)
108+
*/
103109
public void remove(E e) {
104110
Objects.requireNonNull(e);
105111
Node<E> current = head;
@@ -117,7 +123,9 @@ public void remove(E e) {
117123
}
118124
for (int i = 0; i <= layer; i++) {
119125
current.previous(i).setNext(i, current.next(i));
120-
current.next(i).setPrevious(i, current.previous(i));
126+
if (current.next(i) != null) {
127+
current.next(i).setPrevious(i, current.previous(i));
128+
}
121129
}
122130
size--;
123131
}

src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,26 @@ void contains() {
4242
}
4343

4444
@Test
45-
void remove() {
45+
void removeFromHead() {
4646
SkipList<String> skipList = createSkipList();
47+
String mostLeftElement = skipList.get(0);
4748
int initialSize = skipList.size();
4849
print(skipList);
4950

50-
skipList.remove("a");
51+
skipList.remove(mostLeftElement);
52+
53+
print(skipList);
54+
assertEquals(initialSize - 1, skipList.size());
55+
}
56+
57+
@Test
58+
void removeFromTail() {
59+
SkipList<String> skipList = createSkipList();
60+
String mostRightValue = skipList.get(skipList.size() - 1);
61+
int initialSize = skipList.size();
62+
print(skipList);
63+
64+
skipList.remove(mostRightValue);
5165

5266
print(skipList);
5367
assertEquals(initialSize - 1, skipList.size());

0 commit comments

Comments
 (0)