
懂java的大哥帮我看看,面试题,答对了能入职,谢谢了,我没有那么多财富值,江湖救急,只愿有心人帮
1个回答
展开全部
public void offer(int node) {
//两个栈都为空时,优先考虑stack1
if (stack1.isEmpty()&&stack2.isEmpty()) {
stack1.add(node);
return;
}
//如果stack1为空,stack2有元素,直接放入stack2
if (stack1.isEmpty()) {
stack2.add(node);
return;
}
if (stack2.isEmpty()) {
stack1.add(node);
return;
}
}
public int poll() {
//两个栈都为空时,没有元素可以弹出
if (stack1.isEmpty()&&stack2.isEmpty()) {
try {
throw new Exception("stack is empty");
} catch (Exception e) {
}
}
//如果stack1为空,stack2有元素, 将stack2的元素依次放入stack1中,直到最后一个元素,我们弹出。
if (stack1.isEmpty()) {
while (stack2.size()>1) {
stack1.add(stack2.poll());
}
return stack2.poll();
}
if (stack2.isEmpty()) {
while (stack1.size()>1) {
stack2.add(stack1.poll());
}
return stack1.poll();
}
return (Integer) null;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询