How to find nth element from the end of a singly linked list?

后端 未结 28 1107
感动是毒
感动是毒 2020-12-04 06:08

The following function is trying to find the nth to last element of a singly linked list.

For example:

If the elements are

28条回答
  •  天命终不由人
    2020-12-04 06:45

    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;
    }
    

提交回复
热议问题