您的位置:首页 > 其它

How do you find length of a Singly Linked list

2013-11-15 16:37 302 查看
Here is one of the classical questions asked to me on an
interview with multinational Investmentbank after that this question asked to me on several times in other interviews also . what makes this question interesting is that java
developers are not that great with data structure relative to C++ developer which is obvious because of fundamental difference between this two language.C++ is more of system programming language while java is more on application programming , also rich set
of java API allows programmer to skip this kind of basic programming techniques.

anyway lets come back to the question , everybody knows that Linked lists is last element will point to "null" element , so first
answer would most of the times would be "I will use a counter and increment till we reach the end of
the element" e.g.

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());

}

Read more: http://javarevisited.blogspot.com/2010/10/how-do-you-find-length-of-singly-linked.html#ixzz2khZ1aahc
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: