Finding the nth element from the end of a single-linked list is a common data structure problem that can typically be solved using the following methods:
Method One: Two-pass Traversal
Steps:
- First Traversal: Traverse the entire linked list to determine its total length
L. - Second Traversal: Traverse to the (L-n+1)th node from the head, which corresponds to the nth node from the end.
Example Code (assuming Python):
pythonclass ListNode: def __init__(self, value=0, next=None): self.value = value self.next = next def find_nth_from_end(head, n): # First traversal: calculate the linked list length length = 0 current = head while current: length += 1 current = current.next # Calculate the target index from the head target_index = length - n if target_index < 0: return None # n exceeds the list length, return None # Second traversal: find the target node current = head for _ in range(target_index): current = current.next return current
Method Two: Two-pointer Method (Fast and Slow Pointer Method)
Steps:
- Initialize two pointers: Both pointers point to the head node.
- Move the fast pointer: Advance the fast pointer forward by n nodes.
- Move both pointers simultaneously: Move both pointers at the same time; when the fast pointer reaches the end of the linked list, the slow pointer points exactly to the nth node from the end.
Example Code:
pythondef find_nth_from_end(head, n): fast = slow = head # Move the fast pointer forward by n steps for _ in range(n): if fast is None: return None # n exceeds the list length, return None fast = fast.next # Move both pointers simultaneously until fast reaches the end while fast: slow = slow.next fast = fast.next return slow
Among the two methods, Method Two is superior because it can locate the required node in a single traversal with a time complexity of O(L) and a space complexity of O(1). Method One also has a time complexity of O(L), but it requires two traversals of the linked list. Based on efficiency considerations, Method Two (the two-pointer method) is typically the better choice.