Set
Replaces the element at the specified position in the list with the specified element and returns true if element is replaced at the specified position.
public boolean set(int index, int value) {
}
You can leverage the get()
method to find the node and replace its value.
public class LinkedList {
public boolean set(int index, int value) {
Node node = get(index);
if (node == null) return false; // means index is out of range
node.value = value;
return true;
}
}
Testing
public class LinkedListTest {
@Test
void set() {
LinkedList linkedList = new LinkedList();
linkedList.append(11);
linkedList.append(12);
// when index is out of range
assertFalse(linkedList.set(7, 24));
// when index is in range
assertTrue(linkedList.set(0, 10));
assertTrue(linkedList.set(1, 20));
assertEquals(List.of(10, 20), convertToArrayList(linkedList));
}
}
Time Complexity
At worst case setting at desired index requires traversing through node’s next so, this operation has worst-case time complexity of O(n).