Блог пользователя Harshit_04

Автор Harshit_04, история, 16 месяцев назад, По-английски

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?

Полный текст и комментарии »

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится