• + 0 comments
    int getNode(SinglyLinkedListNode* llist, int positionFromTail) {
        // Check for edge cases: empty list or invalid position
        if (llist == nullptr || positionFromTail < 0) {
            // Return an appropriate error or special value.
            // For this example, we return a default value or handle as an error.
            // In a real-world scenario, you might throw an exception.
            return -1; 
        }
    
        auto slow = llist;
        auto fast = llist;
    
        // Move 'fast' pointer 'positionFromTail' steps ahead
        for (int i = 0; i < positionFromTail; ++i) {
            if (fast == nullptr) {
                // The position is out of bounds
                return -1;
            }
            fast = fast->next;
        }
    
        // Now, move both pointers until 'fast' reaches the end
        while (fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next;
        }
    
        return slow->data;
    }