Detailed analysis please refer to the C language version, here is only the implementation of code, the comments are very detailed, I have to say Java API used to be really cool fly
1 PackageCom.xsf.SordForOffer;2 3 ImportJava.util.Stack;4 5 /**6 * Sword refers to offer Pro7, two linked lists to achieve a queue7 * @authorELVIS8 */9 classlistqueue{Ten //define two stacks One PrivateStack<string> Stack1 =NewStack<string>(); A PrivateStack<string> Stack2 =NewStack<string>(); - - //the elements in the queue are placed in the the Public voidaddin (String s) { - Stack1.push (s); -SYSTEM.OUT.PRINTLN ("Input" +s); - } + //The queue output is executed first to detect the presence of data in the Stack2, if there is a direct eject from the STACK2, otherwise the data in the Stack1 out of the stack to Stack2 and then output from Stack2 - PublicString output ()throwsexception{ + //if Stack2 is empty, put Stack1 into Stack2 A if(Stack2.empty ()) { at //Place the value into Stack2 when Stack1 is not empty - while(!Stack1.empty ()) { - Stack2.push (Stack1.pop ()); - } - } - if(Stack2.empty ()) { in Throw NewException ("The queue is empty, cannot output elements"); - to } + returnStack2.pop (); - } the } * Public classPro7linkqueue { $ Public Static voidMain (string[] args)throwsException {Panax NotoginsengListqueue test=Newlistqueue (); -Test.addin ("X"); theTest.addin ("s"); +Test.addin ("F"); ASYSTEM.OUT.PRINTLN ("Output" +test.output ()); the + -Test.addin ("M"); $Test.addin ("D"); $ -SYSTEM.OUT.PRINTLN ("Output" +test.output ()); - the - }Wuyi}
Sword Point offer-7: Two stacks implementation queue (Java)