Monday, August 3, 2009

find nth element from last in singly linked list

Due to popular demand, i am now including programming puzzles also to this blog. enjoy.


Find Nth element from the last in a singly linked list.




click here for answer


Start with two pointers from head of linked list. move second pointer N-1 nodes.
now with first pointer at head, and second pointer at N-1 nodes from head,
move them both by one node with each iteration.
while(p2 ! = null){
p1=p1->next;
p2=p2->next;
}
when p2 reaches the end, p1 will be at nth node from the last.

1 comment:

  1. In general have 2 pointers... and move one pointer to the 9th node and one to the first node and then start moving both one at a time. When the first meets Null or top again what the 2nd one points to is the answer.

    ReplyDelete