From 9b87796ca8d29df4656679b26632fb306c85b11c Mon Sep 17 00:00:00 2001 From: Amman Rizwan Date: Sat, 8 Nov 2025 14:17:54 +0530 Subject: [PATCH] Implement nthToLast method for linked list --- .../chapter-two-linked-lists/NthToLast.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/cracking-the-coding-interview/chapter-two-linked-lists/NthToLast.java b/cracking-the-coding-interview/chapter-two-linked-lists/NthToLast.java index e69de29b..8a1df786 100644 --- a/cracking-the-coding-interview/chapter-two-linked-lists/NthToLast.java +++ b/cracking-the-coding-interview/chapter-two-linked-lists/NthToLast.java @@ -0,0 +1,23 @@ +public class NthToLast { + public static LinkedList nthToLast(LinkedListNode head, int n) { + if (head == null || n <= 0) return null; + + LinkedListNode p1 = head; + LinkedListNode p2 = head; + + // Move p2 ahead by n nodes + for (int i = 0; i < n; i++) { + if (p2 == null) return null; // n is larger than the list length + p2 = p2.next; + } + + // Move both pointers until p2 hits the end + while (p2 != null) { + p1 = p1.next; + p2 = p2.next; + } + + // p1 now points to the Nth to last node + return p1; + } +}