【9. 用两个栈实现队列】剑指offer-JAVA实现

112 阅读1分钟

题目描述: 用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。

解题思路: 思路蛮简单 不写了



public class Nine {
	Stack<Integer> s1 = new Stack<>();
	Stack<Integer> s2 = new Stack<>(); 
	
	public void insertTail(int data) {
		s1.push(data);
	}
	
	public int deleteHead() throws Exception {
		if(s2.isEmpty()){
			while(!s1.isEmpty())
				s2.push(s1.pop());
		}
		if(s2.isEmpty())
			throw new Exception("is empty");
		
		return s2.pop();
	}

	
	
}