Skip to content

Commit d14a5d1

Browse files
authored
Fix SkipList remove operation (TheAlgorithms#3160)
1 parent e59568b commit d14a5d1

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,9 @@ public void remove(E e) {
117117
}
118118
for (int i = 0; i <= layer; i++) {
119119
current.previous(i).setNext(i, current.next(i));
120-
current.next(i).setPrevious(i, current.previous(i));
120+
if (current.next(i) != null) {
121+
current.next(i).setPrevious(i, current.previous(i));
122+
}
121123
}
122124
size--;
123125
}

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)