When adding an element at a certain index using the add(index, element) method in an ArrayList, it places the element at that index, while all the other elements change their indexes by 1 (they move in memory). That's why an ArrayList has the complexity O(n) when adding an element at a certain position.
In case of a doubly LinkedList, I know that the elements have pointers to the previous element and also for the next one.
My question is, when using the add(index, element) method related to a LinkedList, what will actually happen behind the scenes? I know that using the LinkedList the rest of the elements don't move in memory, so how come they can still be placed at a certain index without moving in memory?
Adding a new element to a linked list at a specified index requires walking down the list (from either the head or tail), and then splicing in the new element. The source code for LinkedList#add(int index, E element)
reveals as much:
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
Should the index be pointing to the final item in the list, it simply appends a new node to the end. Otherwise, it calls linkBefore()
, which does a bit of splicing work (I won't bother to include its source code as well).
Note here that adding a new node to a linked list does not necessarily involve moving anything in the already existing list. Rather, it mostly involves moving around references in the background.