public ListNode getNthNodeFromLast(ListNode head, int n) {
ListNode curr = head;
int len = size(head); // takes O(n)// assign current to head of the list curr = head;
// nth node from end means (len-n)th node from start (assuming n is valid)int counter = len - n;
while (counter != 0) {
// n is greater than size (len) of the linked list// current pointer reaches nullif (curr ==null) {
returnnull;
}
curr = curr.next;
counter--;
}
return curr;
}
classSolution {
public ListNode getNthFromEnd(ListNode head, int n) {
ListNode[] ans = ListNode[1];
helper(head, n, ans);
return ans[0];
}
privateinthelper(ListNode head, int n, ListNode[] ans) {
if (head ==null) {
return 0;
}
int index = helper(head.next, n, ans) + 1;
if (index == n) {
ans[0]= head;
}
return index;
}
}
Initialize slow and fast pointers at the head of the list.
Move the fast pointer forward by n steps. If the fast pointer reaches the end before completing n steps, return null (indicating n is greater than the list’s length).
Move both slow and fast pointers one step at a time, maintaining a distance of n nodes between them.
Continue this until the fast pointer reaches the end of the list.
Return the slow pointer, as it will be n nodes from the end, which is the target node.
public ListNode getNthNodeFromLast(ListNode head, int n) {
ListNode slow = head, fast = head;
int i = 0;
// Traverse over list and move fast pointer n nodes ahead while (i < n && fast !=null) {
fast = fast.next;
i++;
}
if (fast ==null) {
returnnull; // List is shorter than n nodes }
// Now, move both pointers together until fast reaches the endwhile (fast !=null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}