314. Find the Nth Node from the End

EasyLinked ListLinked ListTwo Pointer

Given the head of a singly linked list and an integer n, return the value of the nth node from the end of the list.

It is guaranteed that n is valid (1 <= n <= list length).

Use the two-pointer technique: advance the first pointer n steps ahead, then move both pointers until the first reaches NULL.

Input: Head of a singly linked list and integer n (1-based from end).

Output: Integer value of the nth node from the end.

Examples

Example 1
Input: [1,2,3,4,5], 2
Output: 4
Explanation: 2nd from end → index from end: 1st=5, 2nd=4. Return 4.
Example 2
Input: [1,2,3,4,5], 5
Output: 1
Explanation: 5th from end = first node. Return 1.
Example 3
Input: [7], 1
Output: 7
Explanation: Only one node. 1st from end = 7.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →