Skip to content

Commit 410f087

Browse files
fix(lists): leave SkipList size unchanged when removing a missing element (#7666)
1 parent 2319794 commit 410f087

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,9 @@ public void remove(E e) {
121121
current = next;
122122
}
123123
}
124+
if (layer < 0) {
125+
return; // not found, nothing to unlink
126+
}
124127
for (int i = 0; i <= layer; i++) {
125128
current.previous(i).setNext(i, current.next(i));
126129
if (current.next(i) != null) {

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,20 @@ void testClearViaRemovals() {
106106
assertEquals(0, skipList.size());
107107
}
108108

109+
@Test
110+
@DisplayName("Removing a missing element leaves the list unchanged")
111+
void testRemoveMissing() {
112+
skipList.remove("missing");
113+
assertEquals(0, skipList.size());
114+
115+
skipList.add("a");
116+
skipList.add("c");
117+
skipList.remove("b");
118+
assertEquals(2, skipList.size());
119+
assertEquals("a", skipList.get(0));
120+
assertEquals("c", skipList.get(1));
121+
}
122+
109123
private SkipList<String> createSkipList() {
110124
SkipList<String> s = new SkipList<>();
111125
String[] values = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"};

0 commit comments

Comments
 (0)