[Solved] what structure can you simulate recursion iteratively [closed]


You basically half-answered the question yourself: It makes sense to use a stack, since you can push and pop to/from a stack in the same order as the compiler would do it too, if you used recursion. Doing things the way people expect them to happen is a good thing (even if you can do them differently).

A stack is also the easiest solution for the problem and the container with the least overhead, and the elements come out in the order that you usually want when doing recursion, without you needing to do anything special.

In comparison, a queue has a lot more complexity since it has a head and a tail, and memory management is more complicated (a stack is basically just a chunk of memory and a pointer that is incremented/decremented).

Also, when using a queue, elements come out in the order you pushed them in. This may not matter for some problems (e.g. if you just want to iterate every element once and don’t care about the order), but it makes it needlessly complicated to backtrack. For example, when recursively subdividing a block of data or recursively walking a tree, you will first recurse into the left half, then into the left half’s half, and so on.
When you’ve reached the maximum depth, you will want to backtrack one level and recurse into the right half (and backtrack yet another level, and so on). With a stack, this is trivially done with a simple pop. With a queue, you must explicitly remember where to go. It is of course not impossible, but it’s not precisely trivial.

You also mentioned skiplists. Note that a skiplist is not really something simple as a “list”, but a rather complicated structure, much more comparable to a search tree. It also is not a “natural choice” for the problem, and due to its complexity is most definitively not something you want to use for something like recursion (although if one is stubborn enough, it could probably be made to work).

solved what structure can you simulate recursion iteratively [closed]