Thursday, February 24, 2011

Java program to get Nth element from the end of a linked list


Algorithm:
1.Use two pointers.
2.Traverse the list from begining.
3.Start the second pointer only when the first pointer reaches Nth element.

Java implementation:

public Object getNthFromLast(int n)
{
 if(n<1)  return null;
 if(n>nodeCount)
 return null;
 ListNode temp1,temp2;
 temp1=this.headnode;
 temp2=this.headnode;
 int i=1;
 while(i<n) 
{
i++;
temp1=temp1.nextnode;
 }

 while(temp1.nextnode!=null)
 {
temp1=temp1.nextnode;
temp2=temp2.nextnode;
 }

 return temp2.data;

}

No comments: