Write code to return the nth to last element in a linked list.
Approach:
Take 2 pointers front and back.
init front and back with head of the singly link list.
then move front node to nth position.
After that move both front and back at the same time till front.next == null;
back pointer will be pointing to the nth node from end of the singly link list.
P.S. watch out for edge cases.
Code output:
58 -> 57 -> 38 -> 17 -> 83 -> 62 -> 86 -> 52 -> 67 -> 50 -> 49 -> 66 -> 34 -> null
8th node from end: 62
Really loved this post! This page is also helpful:
ReplyDeletehttp://www.programmerinterview.com/index.php/data-structures/find-nth-to-last-element-in-a-linked-list/
This comment has been removed by the author.
ReplyDelete