[Updated] Goldman Sachs Aptitude Test Questions and Answers
Practice List of TCS Digital Coding Questions !!!
Take 50+ FREE!! Online Data Interpretation Mock test to crack any Exams.
Interview Questions and Answers :: Cisco

4. Find nth node from last in single linked list

Answer:

LinkedListNode nthToLast(LinkedListNode head, int n) {
if (head == null || n < 1) {
return null;
}
LinkedListNode p1 = head;
LinkedListNode p2 = head;
for (int j = 0; j < n - 1; ++j) { // skip n-1 steps ahead
if (p2 == null) {
return null; // not found since list size < n
}
p2 = p2.next;
}
while (p2.next != null) {
p1 = p1.next;
p2 = p2.next;
}
return p1;
}

Post Your Answer Here:      Public      Private

Rate This: +1 -0
Report     

Post Your Reply Here:     

Report Error

Report Error

Please Login First Click Here