Using two stacks to implement a queue

Source: Internet
Author: User

Title Description

Implement a queue with two stacks to complete the push and pop operations of the queue. The elements in the queue are of type int.

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/78/0D/wKiom1Z08FiDnl5lAAAnWJmSuig058.png "title=" Untitled. png "alt=" Wkiom1z08fidnl5laaanwjmsuig058.png "/>

The nature of the queue is FIFO first.

, the push operation puts the element into Stack1, the pop operation first takes the element out, presses into the Stack2 and then launches the stack top element from the Stack2. When the Stack2 is not empty, first do not take out stack1 deposit Stack2 operation, but directly from the Stack2 to remove the top element.

Import java.util.stack;public class solution {    static stack <Integer> stack1 = new Stack<Integer> ();    static  Stack<integer> stack2 = new stack<integer> ();     static      public static void push (Int node)       {                    stack1.push (node);              }         public static int pop ()       {        if (Stack2.empty ())          {    while (!stack1.empty ())         {     &nBsp;       stack2.push (Stack1.pop ());         }        }         Int n=stack2.pop ();        return n;     }    public static void main (String[] args)     {                 push (1);         push (2);         push (3); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PR (pop ()); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PR ( Pop ());         pr (pop ());         push (5);         pr (pop ());         push (4); &nbsP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PR (pop ());         public &NBSP;STATIC&NBSP;VOID&NBSP;PR (Int a)         {             system.out.println (a);         }     }                           }




Using two stacks to implement 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.