Skip to content

Commit cd0ad17

Browse files
committed
Merge pull request careermonk#6 from Amay22/master
Added checks for null pointers in LL traversal.
2 parents 552f471 + e6c4f27 commit cd0ad17

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

src/chapter03linkedlists/NthNodeFromEnd.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,15 @@ public ListNode nthNodeFromEnd(ListNode head, int Nth) {
2626
}
2727

2828
public static ListNode nthNodeFromEndIterative(ListNode head, int Nth) {
29+
if(head == null){
30+
return null;
31+
}
2932
ListNode n = head;
3033
// Get nth from the start
3134
for (int i = 0; i < Nth; i++) {
35+
if(nth.next == null){
36+
return null;
37+
}
3238
n = n.next;
3339
}
3440
// Move both the head and nth node so the difference between them is n

0 commit comments

Comments
 (0)