05-面试题9--用两个栈实现队列

package com.my.offer;

import java.util.Stack;

/***
 * 用两个栈实现队列add(),poll(),peek()
 * 定义两个栈结构stackPush(只做压入栈),stackPop(只做弹出栈)
 * 注意两个原则:
 * 1>如果要将stackPush中的数据压入stackPop,必须将stackPush中的数据全部压入stackPop
 * 2>只有在stackPop为空的时候,才能将stackPush中的数据压入stackPop
 * @author asus
 *
 */
public class TwoStacksQueue {
	//创建压入栈
	public Stack<Integer> stackPush; 
	//创建弹出栈
	public Stack<Integer> stackPop; 
	public TwoStacksQueue() {
		stackPush = new Stack<>();
		stackPop = new Stack<>();
	}
	/**
	 * 将stackPush中的元素压入stackPop
	 */
	private void pushToPop() {
		if(stackPop.isEmpty()) {
			//只有当stackPop为空的时候才能进行压入操作
			while(!stackPush.isEmpty()) {
				//一旦进行压入操作,必须将stackPush中的元素全部压入
				stackPop.push(stackPush.pop());
			}
		}		
	}
	/**
	 * 模拟入队操作
	 * @param pushInt
	 */
	public void add(int pushInt) {
		stackPush.push(pushInt);
		pushToPop();
	}
	/**
	 * 模拟出队操作
	 * @return
	 */
	public int poll() {
		//判断队列是否为空
		if(stackPop.isEmpty() && stackPush.isEmpty()) {
			throw new RuntimeException("Queue is empty!");
		}
		pushToPop();
		return stackPop.pop();
	}
	/**
	 * 模拟获取队首元素但不移除
	 * @return
	 */
	public int peek() {
		if(stackPop.isEmpty() && stackPush.isEmpty()) {
			throw new RuntimeException("Queue is empty!");
		}
		pushToPop();
		return stackPop.peek();
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值