Write a program to implement a stack that can return a minimum value of the current elements at any instance
The Approach:-- Have a second stack instance which will hold the minimum values.
- During a push operation if the new data is smaller than the top value in minimum stack push the data into the minimum stack.
- During a pop operation if the popped out value is same as top value in minimum stack pop the top element from minimum stack.
- At any given instance the top element in the minimum stack is the minimum value of all elements in the stack.
C++ program to implement a stack that can return a minimum value of the current elements at any instance
#include <iostream> #include <list> using namespace std; // Basic stack using list class Stack { private: list<int> mData; int count; public: Stack() { count = 0; } ~Stack() {} void push(int data) { mData.push_front(data); count++; } int top() { return mData.front(); } void pop() { mData.pop_front(); count--; } bool empty() { return (count == 0) ? true : false; } int size() { return count; } }; // Min stack class MinStack : public Stack { private: Stack* mMin; public: MinStack() { mMin = new Stack(); } ~MinStack() { delete mMin; } void mpush(int data) { if ( mMin->size() == 0 ) mMin->push(data); else { if ( data < mMin->top() ) mMin->push(data); } push(data); } void mpop() { int val = top(); if ( val == mMin->top() ) mMin->pop(); pop(); } int mmin() { return mMin->top(); } }; // Test program int main() { MinStack* ms = new MinStack(); ms->mpush(10); ms->mpush(20); ms->mpush(30); cout << "Minimum value in stack = " << ms->mmin() << endl; ms->mpush(5); cout << "Minimum value in stack = " << ms->mmin() << endl; ms->mpop(); cout << "Minimum value in stack = " << ms->mmin() << endl; delete ms; }Output:-
Minimum value in stack = 10 Minimum value in stack = 5 Minimum value in stack = 10
0 comments:
Post a Comment