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.
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