两个栈实现一个队列-java

思路:两个栈,stackPop用来出队,stackPush用来入队;

入队时直接将元素压入stackPush里就好了;

出队时先判断stackPop里是否有元素,1)如果有,直接调用stackPop里的pop函数即可,2)如果stackpPop里没有元素,则将stackPush中元素(最后一个元素除外)依次pop出来并push进stackPop里,最后将stackPush中的留下的一个元素pop出来即可。代码如下:

/**
 * @author robin
 * @date 2019年6月14日
 * @time 下午1:46:03 
 */
package com.test1;

import java.util.Stack;

public class TwoStackQueue {
	
	Stack<Integer> stackPop;
	Stack<Integer> stackPush;
	
	public TwoStackQueue() {
		// TODO Auto-generated constructor stub
		stackPop=new Stack<Integer>();
		stackPush=new Stack<Integer>();
	}
	
	public void add(int toPush) {
		stackPush.push(toPush);
	}
	
	public int poll() {
		if (stackPop.isEmpty()&&stackPush.isEmpty()) {
			throw new RuntimeException("Queue is empty!");
		}
		if (!stackPop.isEmpty()) {
			return stackPop.pop();
		}else {
			while (stackPush.size()>1) {
				stackPop.push(stackPush.pop());
			}
			return stackPush.pop();
		}
	}
	
	public int size() {
		return stackPop.size()+stackPush.size();
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TwoStackQueue twoStackQueue=new TwoStackQueue();
		twoStackQueue.add(0);
		System.out.println(twoStackQueue.poll());
		twoStackQueue.add(1);		
		twoStackQueue.add(2);
		twoStackQueue.add(3);
		twoStackQueue.add(4);
		twoStackQueue.add(5);
		while (twoStackQueue.size()>0) {
			System.out.println(twoStackQueue.poll());
		}

	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值