两个栈组成队列

要求:编写一个类,用两个栈来实现队列的基本操作,add , poll , peek

思路:一个push栈,一个pop栈。注意不用每次都更新pop栈,若pop栈里还有上次push进来剩下的,就继续用,顺序是一样的,push栈里什么都不用管,相当于队尾。pop栈的栈顶为队列头

总结:return最好不要放在if-else里面,能最后单写就单独写。把判断条件尽可能合并。

import java.util.*;
public class MyStack{
	private Stack<Integer> pushStack;   //可不用private,这样下面就不用this指代了
	private Stack<Integer> popStack;
	
	public MyStack() {
		this.pushStack = new Stack<Integer>();
		this.popStack = new Stack<Integer>();
	}
	
	public void add(int num) {
		this.pushStack.push(num);
	}
	
	public int poll() {
		if(this.popStack.isEmpty()&&this.pushStack.isEmpty()) {
		    throw new RuntimeException("Empty");
		}else if(this.popStack.isEmpty()) {
			while(!this.pushStack.isEmpty()) {
				this.popStack.push(this.pushStack.pop());
			}
		}
		return this.popStack.pop();
	}
	
	public int peek() {
		if(this.popStack.isEmpty()&&this.pushStack.isEmpty()) {
		    throw new RuntimeException("Empty");
		}else if(this.popStack.isEmpty()) {
			while(!this.pushStack.isEmpty()) {
				this.popStack.push(this.pushStack.pop());
			}
		}
		return this.popStack.peek();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值