• + 0 comments

    I see a lot of solutions posted with double loops and/or a temporary stack of values. It's quite easy to save on repeats and memory with a single pass through the list and keeping track of 2 pointers. Give the one "searching for the end" a "head start" of the amount of provided positions and when you've reached the number, update the pointer to the node with the data.

    public static int getNode(SinglyLinkedListNode llist, int positionFromTail) {
        SinglyLinkedListNode dataNode = llist;
        SinglyLinkedListNode current = llist;
        int ahead = 0;
        while (current.next != null) {
            if (ahead == positionFromTail) {
                dataNode = dataNode.next;
            } else {
                ahead++;
            }
    
            current = current.next;
        }
    
        return dataNode.data;
    }