两个队列实现栈--Java实现

两个栈实现一个队列

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author mazhen
 * @className QueueToStack
 * @Description 两个队列实现栈
 * @date 2021/3/29 10:26
 */
public class QueueToStack {

    Queue<Integer> queue1 = new LinkedList<>();
    Queue<Integer> queue2 = new LinkedList<>();

    //入栈
    public void push(Integer x) {
        queue1.add(x);
    }

    //栈大小
    public int stackSize() {
        return queue1.size() + queue2.size();
    }

    //把一个队列的n-1个元素转出放入到另一个队列
    private void transferToAnother () {
        if (!queue1.isEmpty()) {
            while (queue1.size()>1) {
                queue2.add(queue1.poll());
            }
        } else if (!queue2.isEmpty()) {
            while (queue2.size()>1) {
                queue1.add(queue2.poll());
            }
        }
    }

    //出栈
    public Integer poll() {
        if (stackSize() <= 0) {
            System.out.println("栈已空");
            return -1;
        } else {
            if (queue1.size()>0) {
                transferToAnother();
                return queue1.poll();
            } else if (queue2.size()>0) {
                transferToAnother();
                return queue2.poll();
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        QueueToStack queueToStack = new QueueToStack();
        queueToStack.push(1);
        queueToStack.push(2);
        queueToStack.push(3);
        queueToStack.push(4);
        System.out.println(queueToStack.poll());
        System.out.println(queueToStack.poll());
        System.out.println(queueToStack.poll());
        System.out.println(queueToStack.poll());
    }

}

参考:https://blog.csdn.net/u011328417/article/details/79436120

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值