Sunday, February 19, 2012

nth to last element in a singly linked list.


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


2 comments:

  1. Really loved this post! This page is also helpful:


    http://www.programmerinterview.com/index.php/data-structures/find-nth-to-last-element-in-a-linked-list/

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete