Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- Push (x)-push element x onto stack.
- Pop ()--Removes the element on top of the stack.
- Top ()--Get the top element.
- Getmin ()--Retrieve The minimum element in the stack.
Hide TagsStack Data Structure This is maintained through two stacks, a secondary stack support maintains non-ascending situations, attention needs to be non-ascending, and one for all data maintenance.
#include <iostream>#include<stack>using namespacestd;classMinstack { Public: Stack<int>data; Stack<int>Support ; voidPushintx) {if(Data.empty ()) {Data.push (x); Support.push (x); } Else{data.push (x); if(x<=support.top ()) Support.push (x); } } voidpop () {if(Data.top () = =support.top ()) Support.pop (); Data.pop (); } intTop () {returnData.top (); } intgetmin () {returnSupport.top (); }};intMain () {Minstack myminstack; Myminstack.push (1); cout<<myminstack.getmin () <<Endl; Myminstack.push (2); cout<<myminstack.getmin () <<Endl; Myminstack.push (0); cout<<myminstack.getmin () <<Endl; Myminstack.pop (); Myminstack.pop (); cout<<myminstack.getmin () <<Endl; Myminstack.pop (); return 0;}
[Leetcode] Min Stack Stack