Algorithm: Use two stacks to implement a queue, complete the queue push and pop operations. The elements in the queue are of type int. "The sword means offer"

Source: Internet
Author: User

Algorithm: Use two stacks to implement a queue, complete the queue push and pop operations. The elements in the queue are of type int. "The sword means offer"

The use of the stack to operate, code comments written more clearly: first determine whether the two stack is empty: Second, when the stack is empty, the stack 1 is taken out to stack two, and finally return to the stack two the first value;

The Pop () method and the push method are used mainly:

Package Lg.nowcoder;/** * @Author Liguo * @Description use two stacks to implement a queue to complete the push and pop operations of the queue. The elements in the queue are of type int. * @Data 2018-08-11 21:50*/import Java.util.Stack; Public classSolution1 {Stack<Integer> Stack1 =NewStack <Integer>(); Stack<Integer> Stack2 =NewStack <Integer>();  Public voidPushintnode)                                  {Stack1.push (node);  // directly into the stack     }     Public intpop () {if(Stack1.empty () && stack2.empty ()) { // judgment stack is empty             Throw NewRuntimeException ("Empty linked list" ); }        if(Stack2.empty ()) { // when the second stack is non-empty, copy the first stack to the second stack              while(!Stack1.empty ())            {Stack2.push (Stack1.pop ()); }        }        returnStack2.pop (); // return to the second top of the stack     }}

Algorithm: Use two stacks to implement a queue, complete the queue push and pop operations. The elements in the queue are of type int. "The sword means offer"

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.