Recursion or not?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

In the below class which is the a preferred method for iterating through the
link list? I am told that the first method uses recursion and is less
effiecient than the second method which uses a whiile loop.

Thanks!

public class MyLink
{
private MyLink next;

//get last link in chain
public MyLink GetLastRecursive()
{
if (this.next == null)
{
return this;
}
else
{
return this.next.GetLastRecursive()
}
}

//get last link in chain
public MyLink GetLastWhileLoop()
{
MyLink result = this;
while (result.next != null)
{
result = result.next;
}
return result;
}
}
 
The second, of course. Not only the first method will be slower but it can
lead to a stack overflow if the list is too long.

Recursivity should only be used with complex hierarchical data and not with
something like a linear chain.
 
Back
Top