[Algorithm] to find the smallest element in the stack

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.