• + 0 comments

    My Java solution with linear time complexity and constant space complexity:

    public static int getNode(SinglyLinkedListNode llist, int positionFromTail) {
            int length = getLength(llist);
            int position = (length - 1) - positionFromTail;
            for(int i = 0; i < position; i++){
                llist = llist.next;
            }
            return llist.data;
        }
        
        public static int getLength(SinglyLinkedListNode llist){
            int length = 0;
            while(llist != null){
                length++;
                llist = llist.next;
            }
            return length;
        }