Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If we look at the simplest case, it shouldn't be too hard to generalize from there.</p> <p>Suppose we have a method that looks like this:</p> <pre><code>public void CountToTenInReverse(int curNum) { if (curNum &gt;= 11) return; CountToTen(curNum + 1); Console.WriteLine(curNum); } </code></pre> <p>Let's look at the call stack for <code>CountToTenInReverse(1)</code> to see what's actually happening. After ten calls, we have this:</p> <pre><code>[ CountToTenInReverse(10) ] &lt;---- Top of stack [ CountToTenInReverse(9) ] [ CountToTenInReverse(8) ] [ CountToTenInReverse(7) ] [ CountToTenInReverse(6) ] [ CountToTenInReverse(5) ] [ CountToTenInReverse(4) ] [ CountToTenInReverse(3) ] [ CountToTenInReverse(2) ] [ CountToTenInReverse(1) ] &lt;---- Bottom of stack </code></pre> <p>After the tenth call, we'll hit the base case, and start unwinding the stack, printing numbers as we go. In words, then, our algorithm is "Push numbers onto the stack, stop when we hit 10 numbers, and then pop and print each number." So let's write that with our own stack:</p> <pre><code>public void PrintToTenInReverseNoRecursion() { Stack&lt;int&gt; myStack = new Stack&lt;int&gt;(); for (int i = 0; i &lt; 10; i++) { myStack.Push(i); } for (int i = 0; i &lt; 10; i++) Console.WriteLine(myStack.Pop()); } </code></pre> <p>And now we've successfully converted it over. (Of course this can be done iteratively <em>without</em> a stack, but it was just an example.)</p> <p>The same approach can be taken for other, more complicated algorithms: look at the call stack, and then imitate what it's doing with your own stack.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload