Harshit_04's blog

By Harshit_04, history, 17 months ago, In English

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?

  • Vote: I like it
  • 0
  • Vote: I do not like it

| Write comment?
»
17 months ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

There is no need for returning mini right? Since you already pass by address, your function findMin already does mini=min(mini,curr);

so it basically does nothing in main.

(OK maybe you're learning stacks but this question only requires to find min in O(n) time so why not just push inside a vector instead?)

  • »
    »
    17 months ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it

    Oh yeah that makes sense. I don't need to return it as it will be min when stack becomes empty. And I don't even need to pass the stack by reference. I was just trying to see what variations would occur if I return it. SO that I can learn what actually is happening. But the way I am approaching this idea when to use void or non-void function is it correct. Not limited to finding min. Look at last two lines of my post.

    Thanks for the response!!