两个栈组成队列

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

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

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

import java.util.*;
public class MyStack{
	private Stack pushStack;   //可不用private,这样下面就不用this指代了
	private Stack popStack;
	
	public MyStack() {
		this.pushStack = new Stack();
		this.popStack = new Stack();
	}
	
	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();
	}
}

你可能感兴趣的:(算法,《代码面试指南》)