Interview 9-use two stacks to implement a queue, complete push and pop operations for the queue

Source: Internet
Author: User

    • Topic
      • 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.
    • Ideas:
      • One stack is pressed into the element, and the other stack acts as a buffer, and the stack 1 element is pushed back into the stack 2.
    • Code
Import java.util.stack;/** * Two stacks implementation of a queue * @author MSI */public class requeue{     stack<integer> sk1=new stack< Integer> ();     Stack<integer> sk2=new stack<integer> ();     public void push (int val) {         Sk1.push (val);     }     public int pop () throws exception{//stacks 1 sequentially and presses into the stack 2         if (Sk1.isempty () &&sk2==null) {             throw new Exception ( "Queue is empty");         while (Sk2.isempty ()) {             while (!sk1.isempty ()) {                 Sk2.push (Sk1.pop ());             }         }         return Sk2.pop ();     }    public static void Main (String args[]) throws exception{        requeue q1=new requeue ();        Q1.push (1);        Q1.push (2);        Q1.push (3);        while (q1!=null)        System.out.println (Q1.pop ());               }    }
    • Output
    • 123

        

Interview 9-use two stacks to implement a queue, complete push and pop operations for the 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.