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).

when computer test my code
Test feedback
Initial stack:
(Bottom) 15 4 76 42 39 95 68 22 (Top)
getMin() = 6312224 (Expected: 4)
Input stack was altered.

but my output is this
Initial stack:
(Bottom) 68 15 4 76 42 39 95 68 22 (Top)
getMin() = 4
Input stack was altered.

Second Test feedback is
getMin() = 6312224 (Expected: 17)
Input stack was altered.

my output is
Initial stack:
(Bottom) 49190 8530 85931...(Top)
getMin() = 17
Input stack was altered.


Could you tell me what I am doing wrong?
Thank you.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
  #include <iostream>
#include <stack>
using namespace std;


int getMinElementOfStack(stack<int>& inputStack){
   // Write your implementation of getMin here.
   static stack<int> min;
   static stack<int> init;

        if(min.empty()){
            min.push(inputStack.top());
            init.push(inputStack.top());
            inputStack.pop();
            getMinElementOfStack(inputStack);
        }
        else if (inputStack.empty()){

            cout << "Initial stack: " << endl;
            cout << "(Bottom) ";
            while(!init.empty()){
               cout << init.top() << ' ';
               init.pop();
            }
            cout << "(Top)" << endl;

            cout << "getMin() = "  <<min.top() << endl;
            cout << "Input stack was altered." << endl;
        }
        else{
            init.push(inputStack.top());
            int t = min.top();
            if(inputStack.top() < t){
                min.push(inputStack.top());
                inputStack.pop();
                getMinElementOfStack(inputStack);
            }
            else{
                inputStack.pop();
                getMinElementOfStack(inputStack);
            }
            
        }
}


int main() {
   /* You may use this when testing */
   stack<int> myStack;

   //push data on the stack
   myStack.push(1);
   myStack.push(2);
   myStack.push(3);

   getMinElementOfStack(myStack);



   return 0;
}
I don't understand your restrictions (and the code looks complex too).

Finding a minimun -- the beginner's version:
1
2
3
4
5
6
int min = // big number
int input = 0;
while ( std::cin >> input ) {
  if ( input < min ) min = input;
}
// min has the minimum value 

* There are no "data structures".
* One value at a time is taken from "input source".
* You can take one value at a time from stack. Thus, stack can be an input source.

Is that "too simple"?
Topic archived. No new replies allowed.