I want to convert the following program into a non-recursive code using a stack and a loop:
void write(int n) {
if (n>0) {
write(n-1);
cout << n << " ";
write(n-1);
}
}
And here is the code I am using but that currently does not work, and I do not know why:
stack<int> S;
S.push(n);
while (not S.empty()) {
int k = S.top();
S.pop()
if (k>0) {
S.push(k-1);
cout<<k<<" ";
S.push(k-1);
}
}
It doesn't work and I have no idea how to simulate that recursion. I thought it was enough to push into the stack the equivalent recursive call.
thanks
S.push(k-1);