Understanding Recursion...Am I on the right path?

Правка en1, от Harshit_04, 2023-07-13 03:25:13

I am learning stacks and practising stacks question. I was trying to find min in a stack and noticed i need to traverse it once in a straight line to find the min. I don't want to come back from the end. So it is optimal to use void. Like this:

~~~~~

include <bits/stdc++.h>

using namespace std;

void findMin(stack &s,int &mini){

//cout<<mini<<endl;
if(s.empty()){
    return ;
}

int curr=s.top();
mini=min(mini,curr);
s.pop();


findMin(s,mini);

s.push(curr);

}

int main() { stack s; s.push(1); s.push(2); s.push(3); s.push(4);

int x=INT_MAX;

findMin(s,x);

cout<<x;

return 0;

}~~~~~ I know it is possible to use int like this:

include <bits/stdc++.h>

using namespace std;

int findMin(stack &s,int &mini){

//cout<<mini<<endl;
if(s.size()==1){
    return s.top();
}

int curr=s.top();
s.pop();
mini=min(mini,findMin(s,mini));

s.push(curr);

return mini;

}

int main() { stack s; s.push(1); s.push(2); s.push(3); s.push(4);

int x=INT_MAX;

int y=findMin(s,x);

cout<<x;

return 0;

}

But my question is this. When we are trying to carry something while coming backwards and comapre it to other values we use non void function. And when we just want to compute somthing straight we can use void. Am I right in thinking this?

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en4 Английский Harshit_04 2023-07-13 03:28:06 2 Tiny change: 'his:\n\n\n`\n#include <' -> 'his:\n\n\n\n`#include <'
en3 Английский Harshit_04 2023-07-13 03:27:27 6
en2 Английский Harshit_04 2023-07-13 03:26:20 16
en1 Английский Harshit_04 2023-07-13 03:25:13 1635 Initial revision (published)