算法:(1)两个栈实现队列

一、题目描述

使用两个栈实现队列。

二、实现和验证

1.代码

import java.util.Stack;
import java.util.logging.Logger;

/**
 * Created by Administrator on 2020/1/31.
 * 题目:两个栈实现队列
 *
 * 思路:
 * (1)第一个栈存放写队列的数据。
 * (2)第二个栈存放将要移除队列的数据。
 * -》第二个栈如果没数据,第一个栈里的数据依次弹出压入第二个栈;
 * -》第二个栈如果有数据,则直接pop出栈顶的数据
 *
 */
public class TwoStackQueue {

    /**
     * 写入栈
     */
    private Stack<Integer> input=new Stack<>();

    /**
     * 输出栈
     */
    private Stack<Integer> out=new Stack<>();

    /**
     * 入队
     * @param t
     */
    public void enqueue(int t){
        input.push(t);
    }

    /**
     * 出队
     * @return
     */
    public int dequeue(){

        if(out.isEmpty()){
            while (!input.isEmpty()){
                out.push(input.pop());
            }
        }

        return out.pop();
    }

    /**
     * 队列中总数
     * @return
     */
    public int getSize(){
        return input.size()+out.size();
    }

    public static void main(String[] args) {

        TwoStackQueue twoStackQueue=new TwoStackQueue();
        twoStackQueue.enqueue(1);
        twoStackQueue.enqueue(4);
        twoStackQueue.enqueue(5);
        twoStackQueue.enqueue(6);
        twoStackQueue.enqueue(19);

        int size=twoStackQueue.getSize();

        for (int i = 0; i < size; i++) {
            System.out.println(twoStackQueue.dequeue());
        }
    }
}

2.验证结果

1
4
5
6
19

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值