DOUBLY LINKED LISTS
Insert element at a specified index
27
/**
* Inserts the specified element at the specified index.
*
* @param index
* the index to insert the element
* @param element
* the element to insert
* @pre 0<=index<=size
*/
public void add(int index, E element) {
// check whether index is valid
if (index > size || index < 0){
throw new IndexOutOfBoundsException("Index " + index + " out of bounds");
}!
// if index is 0, call addFirst
if (index == 0) {
addFirst(element);!
// if index is n, call addLast
} else if (index == size()) {
addLast(element);!
// else
} else {
// Make two new Node references, previous and finger. Set previous to null and finger to head
Node previous = null;
Node finger = head;
// search for index-th position. Set previous to finger and move finger to next position
while (index > 0) {
previous = finger;
finger = finger.next;
index--;
}
// create new Node, update its element, and fix its pointers taking into account where finger and previous are
Node current = new Node();
current.element = element;
current.next = finger;
current.prev = previous;
previous.next = current;
finger.prev = current;
// increase number of nodes
size++;
}
}
This is more work. We will need to double down on our trick and have two pointers. Let's call them previous and finger. Finger will start at the head and previous will trail
it one step behind. Eventually, finger will reach the index we want to insert the new node which we will reference with current. We will use these two pointers, to make the
previous point to current (and vice versa), and current point to finger (and vice versa).!