Help with finding minimum element in a stack

I am trying to code finding minimum element in a stack by only using stack(no other data structures, such as vectors or lists, are allowed).

Last edited on
The program crashes on line 12. Since min is a local variable it is guaranteed that it is empty at any time getMinElementOfStack(...) is called.

Try to make it static: static stack<int> min;
You never return anything. Presumably you should return the minimum element.

Lines 16-17 indicate a problem. What will you return in this case? If the stack is empty then there is NO mimimum element. To handle this I suggest you change the function like so:
// Find the minimum value of the stack. If the stack is empty then return false and leave stk and result unchanged. Otherwise set result to the minimum value and return true. Stk is modified during the call, but returned to it's original value by the time this returns.
1
2
3
4
bool getMinElementOfStack(stack<int> &stk, int &result)
{
    ...
}


As for the code, why not do it in a loop:
1
2
3
4
5
6
7
8
create a temp stack
while stk isn't empty {
    pop stk
    if value is less than min then result = min
    push value onto temp stack.
}

stk = temp stack 

Topic archived. No new replies allowed.