Skip to content

Commit 552f471

Browse files
committed
Merge pull request careermonk#5 from Amay22/master
Added function to return nth-last node in LL
2 parents e94073e + 0beff31 commit 552f471

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/chapter03linkedlists/NthNodeFromEnd.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,19 @@ public ListNode nthNodeFromEnd(ListNode head, int Nth) {
2424
}
2525
return null;
2626
}
27+
28+
public static ListNode nthNodeFromEndIterative(ListNode head, int Nth) {
29+
ListNode n = head;
30+
// Get nth from the start
31+
for (int i = 0; i < Nth; i++) {
32+
n = n.next;
33+
}
34+
// Move both the head and nth node so the difference between them is n
35+
// Thus we get the nth node from the end
36+
while(n != null){
37+
head = head.next;
38+
n = n.next;
39+
}
40+
return head;
41+
}
2742
}

0 commit comments

Comments
 (0)