I have a program that has three functions, one that pushes to stack, second that pops from stack, and third that checks the minimum in that stack.
It is easy to check the minimum when we are pushing, as we can check at every new push if the minimum changes or not. However, what if the user popped the minimum value, how can I go back to the min value of the one before it? I thought of using nodes. I know I could use a vector instead of a stack, however I want to use the stack function and be able to still find the minimum even if the user popped the last minimum.
Can we keep track of the minimum numbers with a node or is a vector the only way?
Here is my code:
#include <iostream>
#include <stack>
using namespace std;
void myPush(int num, stack<int>& myStack, int &min);
void myPop(stack<int>& myStack, int &min);
int main()
{
int x=0;
int choice;
int n;
int dmin= 2147483646;
stack<int> myStack;
while( x==0) {
cout << "stack menu: " << endl; //this is just a menu
cout << "1- for push " << endl;
cout << "2- for pop " << endl;
cout << "3- for min " << endl;
cout << "4-exit " << endl;
cin >> choice;
if(choice == 1)
{
cout << " I want to push: " << endl;
cin >> n;
myPush(n, myStack, dmin);
}
else if(choice == 2)
{
cout << "popped: " << endl;
myPop(myStack, dmin);
}
else if(choice == 3)
{
cout << "minimum is: " << endl;
cout << dmin;
}
else
x=1; //this will exit the menu
}
}
void myPush(int num, stack<int>& myStack, int &min)
{
if(num <= min) //check if it's the new minimum
min = num;
myStack.push(num); //pushes new num
}
void myPop(stack<int>& myStack, int &min)
{
cout << "popping: " << myStack.top() << endl; //tells the user what we are popping
if( min == myStack.top()) //let the user know that minimum changed(DISASTER!!!)
cout<< "min changed " << endl;
myStack.pop(); //pop that value(Hopefully not the min !)
}