MinStakc.cpp
#include <iostream>using namespace std; #include <stack>template<class t>class stack{public: void push (const t& x) { //into the stacks _stack.push (x); if (_minstack.empty ()) _minstack.push (x); Else{ _minstack.push ((_minstack.top () > x ) x : _ Minstack.top ()); } } void pop () { //out Stack _stack.pop (); _minstack.pop (); } t getmin () { Minimum value of //stack cout << _minstack.top () << endl; return _minstack.top (); }private: stack<t> _stack; stack<t> _minstack;}; Void test () { stack<int> s; s.push (1); s.push (2); s.push (5); s.Push (7) ; s.push (8); s.getmin (); s.pop (); s.getmin (); s.pop (); s.getmin (); s.Pop ();} Int main () { test (); return 0;}
This article is from the "Molova" blog, make sure to keep this source http://molova.blog.51cto.com/10594266/1711380
C + +: Implement a stack that includes a stack, a stack function, and a return minimum, requiring a time complexity of O (1)