• + 0 comments
    public static int getNode(SinglyLinkedListNode head, int positionFromTail) {
        // Create two pointers, both starting at the head
        SinglyLinkedListNode fast = head;
        SinglyLinkedListNode slow = head;
    
        // Move the 'fast' pointer 'positionFromTail' steps ahead
        for (int i = 0; i < positionFromTail; i++) {
            fast = fast.next;
        }
    
        // Now move both 'fast' and 'slow' one step at a time
        // When 'fast' reaches the last node, 'slow' will be at the target node
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
    
        // 'slow' is now pointing to the node that is 'positionFromTail' from the end
        return slow.data;
    }