Interview Question
Country: United States
Recursion actually needs to switch/restore back the states correctly. This restoration can happen effectively through pointers as they are address-based.
Hence, linked lists are preferred.
I didn't understand the "best". But the stack is must have datas structure for recursion.
Hi USTChucat, again I am confused: we know that certain recursive algorithms (merge sort etc) work on array, and of course there are other algorithms (tree walker etc) using stacks. So what exactly does "best" mean here, and what's your reason to pick stack over, say, array? Thanks.
I thought it was asking us which kind of data structure was best fit for implementing recursion in compilers, rather than which kind of data structure should be used in implementing recursion algorithm.
Of those options, only the queue is fundamentally wrong.
However, none of the other options are particularly good.
A better option would be a tree, as the recursion might require many evaluations at each level, and a tree will be more flexible for that, and also allow parallelisation if the problem is suitable..
As this is an interview question, going beyond the presented options is probably not a bad thing.
Suppose we have three functions in recursion. For example. f1,f2, and f3.
f1 {
f2{
f3{
}
}
}
So complier should store f1 , f2 in such way that our program correctly jumb back to f2 after executing f3. And we know STACK works as "Last in First out" so f3 goes last and comes first according to concept. This what I can suggest here.
the concept of stack is necessary,but the successful implementation of the stack using linked list can make it much better through the top and head pointers the push,pop,peek and empty can be provided in O(1) that to with pointer access it is made fast.So considering recursion the idea of stack is important but the implementation is made via the list for maintaining the states.
Stack
- sneha February 06, 2013