190422打卡:栈实现队列

问题描述:
如何仅用栈实现队列?
思路:用两个栈实现队列
在这里插入图片描述
在队列入队的时候元素进入stackPush栈,元素出队的时候,将stackPush栈里面的元素倒入stackPop栈中,然后依次从stackPop栈里面弹出,在倒数据时有两个条件:1.如果要倒数据就一次性倒完,2.如果help栈中有元素则不能倒,只要满足该条件,就可以倒数据,并且倒数据可以发生在任何时刻

package code001_code010;

import java.util.Stack;

public class Code_002_StackToQueue {
	
	public static class StackToQueue{
		private Stack<Integer> stackPush;
		private Stack<Integer> stackPop;
		
		public StackToQueue() {
			stackPush = new Stack<>();
			stackPop = new Stack<>();
		}
		
		public void enqueue(int obj) {
			stackPush.push(obj);
		}
		
		public int dequeue() {
			if (stackPush.isEmpty() && stackPop.isEmpty()) {
				throw new RuntimeException("Dequeue failed, Queue is null");
			} else if (stackPop.isEmpty()) {
				while(!stackPush.isEmpty()) {
					stackPop.push(stackPush.pop());					
				}
			}
			
			return stackPop.pop();
		}
		
		public int peek() {
			if (stackPush.isEmpty() && stackPop.isEmpty()) {
				throw new RuntimeException("Dequeue failed, Queue is null");
			} else if (stackPop.isEmpty()) {
				while(stackPush.size() > 0) {
					stackPop.push(stackPush.pop());					
				}
			}
			
			return stackPop.peek();
		}
		
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值