public Node findNthFromLast(int nth){
Node firstPointer=first;
Node secondPointer=first;
for(int i=0;i<nth;i++){
firstPointer=firstPointer.next;
}
while(firstPointer!=null){
firstPointer=firstPointer.next;
secondPointer=secondPointer.next;
}
return secondPointer;
}
1) The basic concept of this program is to create 2 pointers , first and second.
2) Now, say we have to find nth element from the last.
3) Idea is to create a gap of n between first pointer and second pointer. That is some thing we do by moving the first pointer to nth position from starting.
4) Now iterate the first and second pointer together till first pointer becomes null.
1) The basic concept of this program is to create 2 pointers , first and second.
2) Now, say we have to find nth element from the last.
3) Idea is to create a gap of n between first pointer and second pointer. That is some thing we do by moving the first pointer to nth position from starting.
4) Now iterate the first and second pointer together till first pointer becomes null.