The time complexity required for the Getmin method of the stack and for the push and pop methods is O (1).
Design Plan One:
PackageCoding.chapter01;ImportJava.util.Stack;/*** Created by Needle on 2017/3/17.*/ Public classGetminstack {Privatestack<int> datastack;//stack of stored data Privatestack<int> minstack;//stack that stores the minimum value PublicGetminstack () {Datastack=Newstack<int>(); Minstack=Newstack<int>(); } Public intgetmin () {if(Minstack.isempty ())Throw NewRuntimeException ("The Stack is empty ....")); Else returnMinstack.peek ();//gets the value of the top element of the stack, not out of the stack } Public voidPushintnum) { //operation on Minstack if(Minstack.isempty ()) Minstack.push (num); Else if(Num <=getmin ()) Minstack.push (num); //working with the DatastackDatastack.push (num); } Public intpop () {if(Minstack.isempty ())Throw NewRuntimeException ("The Stack is empty ....")); intValue = Datastack.pop ();//datastack normal out Stack if(Value = = Getmin ())//Minstack the stack only in the same situationMinstack.pop (); returnvalue; }}
Design Scenario Two:
PackageCoding.chapter01;ImportJava.util.Stack;/*** Created by Needle on 2017/3/19.*/ Public classGetMinStack2 {Privatestack<int> datastack;//stack of saved data Privatestack<int> minstack;//the stack that holds the minimum value PublicGetMinStack2 (stack<int> Datastack, stack<int>minstack) { This. Datastack =Datastack; This. Minstack =Minstack; } //out of the stack Public intpop () {if(Datastack.isempty ())Throw NewRuntimeException ("Error:stack is empty!"); intValue =Datastack.pop (); Minstack.pop (); returnvalue; } Public voidPushintnum) {Datastack.push (num); if(Minstack.isempty ()) {minstack.push (num); } Else if(Num <=Minstack.peek ()) Minstack.push (num); ElseMinstack.push (Minstack.peek ()); } Public intGetMin2 () {if(Minstack.isempty ())Throw NewRuntimeException ("Error:stack is empty!"); returnMinstack.peek (); }}
The design of an algorithm a stack structure with Getmin method