The following function is trying to find the nth to last element of a singly linked list.
For example:
If the elements are
You can just loop through the linkedlist and get the size. Once you have the size you can find the n'th term in 2n which is O(n) still.
public T nthToLast(int n) {
// return null if linkedlist is empty
if (head == null) return null;
// declare placeholder where size of linkedlist will be stored
// we are hoping that size of linkedlist is less than MAX of INT
int size = 0;
// This is O(n) for sure
Node i = head;
while (i.next != null) {
size += 1;
i = i.next;
}
// if user chose something outside the size of the linkedlist return null
if (size < n)
return null;
// This is O(n) if n == size
i = head;
while(size > n) {
size--;
i = i.next;
}
// Time complexity = n + n = 2n
// therefore O(n)
return i.value;
}