Java two stack implements a queue

Source: Internet
Author: User

Ideas

When you queue, press the element into the S1. when out of the team, determine whether S2 is empty, if not empty, the top element is directly ejected, if empty, S1 elements are "poured" S2, the last element ejected and out of the team.

 Public classQuenewithtwostacks {PrivateStack<integer>Stack1; PrivateStack<integer>Stack2;  Publicquenewithtwostacks () {Stack1=NewStack<integer>(); Stack2=NewStack<integer>(); }         PublicInteger Poll () {if(Stack1.isempty () &&stack2.isempty ())return NULL; Integer Re=NULL; if(!Stack2.isempty ()) {Re=Stack2.pop (); } Else {             while(!Stack1.isempty ()) {Re=Stack1.pop ();            Stack2.push (re);        } poll (); }        returnre; }         PublicInteger Insert (into) {stack1.push (o); returno; }         Public Static voidMain (string[] args) {quenewithtwostacks qw=Newquenewithtwostacks (); Qw.insert (2); Qw.insert (1); Qw.insert (3); Qw.insert (4); System.out.println ("Out of stack----" +Qw.poll ()); Qw.insert (5); Qw.insert (9); System.out.println ("Out of stack----" +Qw.poll ()); System.out.println ("Out of stack----" +Qw.poll ()); }}

Java two stack implements a queue

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.