How to use the time complexity of O (1) to find the smallest element in the stack
Problem Solving Ideas:
We often use space in exchange for time to increase the complexity of time. We can use two stack structures, one stack to store the data, and the other stack to store the smallest elements in the stack. The idea is as follows: if the current stack element is smaller than the minimum value in the original stack, the value is pressed into the stack that holds the smallest element, and at the time of the stack, if the element that is currently in the stack is exactly the minimum value in the current stack, the top element that holds the minimum value is also out of the stack, making the current
The implementation code is as follows:
Package to find the smallest element in the stack;/** * Implementing stacks in a linked list * @author Dream * * @param <E> * * Public classmystack<e> {node<e> top =NULL; PublicBooleanIsEmpty(){returntop = =NULL; } Public void Push(E data) {Node<e> NewNode =Newnode<e> (data); Newnode.next = top; top = NewNode; } PublicEPop(){if(IsEmpty ()) {return NULL; } E data = Top.data; top = Top.next;returnData } PublicEPeek(){if(IsEmpty ()) {return NULL; }returnTop.data; }}
package 求栈中最小元素;publicclass Node<E> { null; E data; publicNode(E data){ this.data = data; }}
Package to find the smallest element in the stack;ImportJavax.XML.Crypto.DSig.KeyInfo.RetrievalMethod; PublicClass MyStack1 {Mystack<Integer>Elem Mystack<Integer> min; PublicMyStack1 () {Elem= NewMystack<>();min = NewMystack<>(); } Public voidPush (intData) {Elem.PushData);if(min.IsEmpty ()) {min.PushData); }Else{if(Data < min.Peek ()) {min.PushData); } } } Publicint pop () {int Topdata=Elem.Peek (); Elem.Pop ();if(Topdata== min()){min.Pop (); }returnTopdata; } PublicIntmin(){if(min.IsEmpty ()) {return Integer.Max_value; }Else{return min.Peek (); } }}
[Algorithm] to find the smallest element in the stack