Stack for Min function implementation

Source: Internet
Author: User
Package Structure. stack_queue; import java. util. Stack;/*** defines the data structure of the stack. A Min function must be added to obtain the minimum element of the stack. The time complexity of the min, push, and pop functions is O (1 ). ** @ Author toy **/public class stack_min {stack <integer> S = new stack <integer> (); stack <integer> mins = new stack <integer> (); public void push (INT d) {S. push (d); If (mins. isempty () {mins. push (0);} else {int minindex = mins. peek (); If (d <S. get (minindex) {mins. push (S. size ()-1);} else {mins. push (minindex) ;}} public int POP () {If (S. isempty () {system. out. println ("Empty stack"); Return-1;} else {mins. pop (); Return S. pop () ;}} public int min () {If (mins. isempty () {system. out. println ("Empty stack"); Return-1;} else {int minindex = mins. peek (); Return S. get (minindex) ;}}/*** @ Param ARGs */public static void main (string [] ARGs) {int [] A = new int [] {3, 4, 2, 5, 1, 6}; stack_min S = new stack_min (); For (INT I = 0; I <. length; I ++) {S. push (A [I]);} system. out. println (S. min (); S. pop (); S. pop (); system. out. println (S. min (); S. pop (); S. pop (); system. out. println (S. min ());}}

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.