两个栈实现队列

本文介绍了一种使用两个栈来实现队列的方法,并通过Java泛型进行代码实现。该实现方式能够灵活地处理不同类型的数据,如字符串和整数等。

题目很简单,今天看了下Java泛型的东西,用泛型改写了一下:

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<>(); // 入队
    private Stack<T> s2 = new Stack<>(); // 出队

    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());
    }

    // 测试
    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());
    }
}

  

转载于:https://www.cnblogs.com/duanguyuan/p/6214291.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值