Defines the data structure of the stack, requiring the addition of a min function to get the smallest element of the stack. The time complexity of the function min, pop and push is called O (1);
Method: A secondary stack is used to hold the smallest element. When the push operation is carried out, the smallest element in the stack is pushed into the secondary stack simultaneously, while the pop operation pops off the stack top element in the auxiliary stack. This is always the smallest element stored in the secondary stack corresponding to the position of the element stack.
#include <iostream> #include <stack>using namespace Std;template<class t>class stackwithmin{public: void push (const T value); void Pop (); T min ();p rivate:stack<t> datastack;stack<t> minstack;}; Template <class t>void stackwithmin<t>::p ush (T value) {Datastack.push (value); if (Minstack.size () ==0) { Minstack.push (value);} else if (Value<minstack.top ()) {Minstack.push (value);} Else{minstack.push (Minstack.top ());}} Template <class t>void Stackwithmin<t>::p op () {Datastack.pop (); Minstack.pop ();} Template <class t>t stackwithmin<t>::min () {T p;p=minstack.top (); return p;} int main () {int t; Stackwithmin<int> S;s.push (3); S.push (1); S.push (5); S.push (6); S.push (0); T=s.min ();cout<< "min:" < <t<<endl;s.pop (); T=s.min ();cout<< "min:" <<t<<endl;return 0;}
Design a stack that contains the Min function