Inserting in Front

Linked List Front Insertion

Inserting at Random

Front and Random Insertion Times

Code for Linked List Add
public void add(int i, E x) {
Node<E> nd = new Node<E>();
nd.value = x;
if (i == 0) {
nd.next = this.head;
this.head = nd;
} else {
Node<E> pred = getNode(i - 1);
Node<E> succ = pred.next;
pred.next = nd;
nd.next = succ;
}
++size;
}
Code for Linked List getNode
private Node<E> getNode(int i) {
// check if i is a valid index
if (i < 0 || i >= size) return null;
Node<E> cur = head;
// find the i-th successor of the head
for (int j = 0; j < i; ++j) {
cur = cur.next;
}
return cur;
}
Code for Array Add
public void add(int i, E x) {
if (size == capacity) {
increaseCapacity();
}
++size;
Object cur = x;
for (int j = i; j < size; ++j) {
Object next = contents[j];
contents[j] = cur;
cur = next;
}
}
Code for increaseCapacity
private void increaseCapacity() {
// create a new array with larger capacity
Object[] bigContents = new Object[capacity + 1];
// copy contents to bigContents
for (int i = 0; i < capacity; ++i) {
bigContents[i] = contents[i];
}
// set contents to refer to the new array
contents = bigContents;
// update this.capacity accordingly
capacity = capacity + 1;
}