Sword Point offer-7: Two stacks implementation queue (Java)

Source: Internet
Author: User

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)

Related Article

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.