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