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:
Post a Comment