Design a queue with two stacks

Source: Internet
Author: User


Idea: Use two stacks, one for receiving (in), and the other for output (out). If out is empty before output, import the data in out.


Import Java. util. stack; // use two stacks to design a queue p142public class myqueue <t> {stack <t> In; stack <t> out; Public myqueue () {In = new stack <t> (); out = new stack <t> ();} public void enqueue (t a) {In. push (a);} public t dequeue () {shiftitems (); Return out. pop ();} public t PEEK () {shiftitems (); Return out. peek ();} private void shiftitems () {If (! Out. isempty () return; while (! In. isempty () {out. push (in. pop () ;}} public static void main (string [] ARGs) {myqueue <integer> queue = new myqueue <integer> (); queue. enqueue (1); queue. enqueue (2); queue. enqueue (3); system. out. println (queue. dequeue (); queue. enqueue (4); system. out. println (queue. dequeue (); system. out. println (queue. dequeue (); system. out. println (queue. dequeue ());}}


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: 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.