The topic describes the data structure of the definition stack, in this type to implement a can get the minimum stack element of the Min function solution one: The idea: the use of Java's own iterative function for processing.
Public classsolution{/** * @paramargs*/Stack<Integer> stack =NewStack<integer>(); Public voidPushintnode) {Stack.push (node); } Public voidpop () {stack.pop (); } Public intTop () {returnStack.peek ();//the top value here is the. Peek () function, and don't forget the intrinsic function of the stack itself } Public intmin () {intmin = Stack.peek ();//first number out stack intTMP = 0; Iterator<Integer> iterator = Stack.iterator ();//iteration, to the stack while(Iterator.hasnext ()) {tmp=Iterator.next (); if(min>tmp) {min=tmp; } } returnmin; } Public Static voidMain (string[] args)throwsException {//TODO auto-generated Method StubMin_stack ms=NewMin_stack (); Ms.push (3); Ms.push (2); Ms.push (3); System.out.println (Ms.min ()); }}
Solution Two:
Idea: Save the data with one stack data, and save it with the decimal of the stack with another stack min. For example: Data in the secondary stack: 5,4,3,8,9,10,111,12,1
Then the second into the stack in min: 5,4,3,1
Each time you enter the stack, if the elements in the stack are smaller or equal to the top of the stack in min, it is not as good as the stack.
Public classsolution{Stack<Integer> data =NewStack<integer>(); Stack<Integer> min =NewStack<integer>(); Integer Temp=NULL; Public voidPushintnode) { if(temp!=NULL){ if(Node <temp) {Min.push (node); Temp= node;//Temp is the minimum value saved} data.push (node); }Else{Temp=node; Data.push (node); Min.push (node); } } Public intpop () {intnum =Data.pop (); intnum2 =Min.pop (); if(num! = num2) {//determine if the stack min already existsMin.push (num2); } } Public intTop () {intnum =Data.pop (); Data.push (num); returnnum; } Public intmin () {intnum =Min.pop (); Min.push (num); returnnum; }}
Solution Three:
/*
* 1.dataStack为存储数据的栈,minStack为存储最小值的栈;
* 2.push的时候将value值与minStack中的top值比较,小则minStack push value,大则push top值
*/
class Solution {public: stack<int> datastack, minstack; void push (int value) { Datastack.push (value); if (Minstack.empty ()) { Minstack.push (value); } Else { int min = minstack.peek ();
if (value<min) {
Minstack.push (value);
}else{
Minstack.push (min);
}
}
} void pop () { datastack.pop (); Minstack.pop (); } int Top () { return datastack.peek (); } int min () { return minstack.peek (); }};
Stack containing the Min function