find node from pos linkedlist c++

// C++ code to find node at given position in a linked list

#include <iostream>
using namespace std;

// Linked list node structure
struct Node {
    int data;
    struct Node* next;
    Node(int val) {
        data = val;
        next = nullptr;
    }
};

// Function to find node at given position
Node getNodeAtPosition(Node head, int pos) {
    Node* current = head;
    int count = 0;
    while (current != nullptr) {
        if (count == pos) {
            return current;
        }
        count++;
        current = current->next;
    }
    return nullptr;
}

// Example usage
int main() {
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);

    int position = 2; // Change position as needed
    Node* result = getNodeAtPosition(head, position);

    if (result != nullptr) {
        cout << "Node at position " << position << " is: " << result->data << endl;
    } else {
        cout << "Position " << position << " is invalid" << endl;
    }

    return 0;
}