Iterative Solutions
public int length(){
int count=0;
Node current = this.head;
while(current != null){
count++;
current=current.next()
}
return count;
}
If you answer this question without any difficulty most interviewer will ask you to write a "recursive" solution for this just to check how you deal with recursion if your first answer would have been recursive they will ask you to write an "iterative solution" as shown above.
Recursive Solution:
public int length(Node current){
if(current == null) //base case
return 0;
return 1+length(current.next());
}
No comments:
Post a Comment