#include
using namespace std;
// Node structure
struct Node {
int data;
Node* next;
Node(int val) {
data = val;
next = NULL;
}
};
// Function to find Nth node from end
Node* nthFromEnd(Node* head, int n) {
if (!head) return NULL;
Node* first = head;
Node* second = head;
// Move first pointer n steps ahead
for (int i = 0; i length of list
first = first->next;
}
// Move both until first reaches the end
while (first != NULL) {
first = first->next;
second = second->next;
}
return second; // second points to nth node from last
}
// Helper function to print linked list
void printList(Node* head) {
while (head != NULL) {
cout data next;
}
cout 2->3->4->5
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);
int n = 2;
Node* result = nthFromEnd(head, n);
if (result != NULL)
cout data << endl;
else
cout << "List is shorter than " << n << " nodes." << endl;
return 0;
}