Two stacks to implement a queue

Source: Internet
Author: User

The topic is very simple, today looked at the Java generic type of things, with the generic rewrite a bit:

Package Com.wy.oj;import java.util.stack;/** * Created by WY on 2016/12/23 023. */public class Twostackqueue<t> {private stack<t> S1 = new stack<> ();//Queue Private Stack<t&gt ; S2 = new stack<> ();        Out of public T pop () {if (IsEmpty ()) return null;        if (!s2.isempty ()) return S2.pop ();            else {while (!s1.isempty ()) S2.push (S1.pop ());        return S2.pop ();    }} public void push (T item) {S1.push (item);    } public int size () {return s1.size () + s2.size ();    } public boolean IsEmpty () {return (S1.isempty () && s2.isempty ()); }//test public static void main (string[] args) {twostackqueue<string> qs = new Twostackqueue<> ()        ;        For (String s: "Qing li si nian chun". Split ("")) Qs.push (s);        for (int i=0; i<3; ++i) System.out.println (Qs.pop ());        System.out.println (); For (String s: "tEn Zi Jing ". Split (")) Qs.push (s);        while (!qs.isempty ()) System.out.println (Qs.pop ());        Twostackqueue<integer> qi = new twostackqueue<> ();        for (int i=10; i<100; i=2*i) Qi.push (i);    while (!qi.isempty ()) System.out.println (Qi.pop ()); }}

  

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.