改进:之前没有优化,仅是每次要delete时整两次循环返还给stk1。
去除一个循环----即stk1用来存数据,stk2输出数据。仅需在stk2中无数据时才进行一次倒换(循环)。
class CQueue {
Stack<Integer> stk1;
Stack<Integer> stk2;
public CQueue() {
stk1 = new Stack<Integer>();
stk2 = new Stack<Integer>();
}
public void appendTail(int value) {
stk1.push(value);
}
public int deleteHead() {
if(!stk2.isEmpty()){
return stk2.pop();
}
if(stk1.isEmpty()){
return -1;
}
while(!stk1.isEmpty()){
stk2.push(stk1.pop());
}
return stk2.pop();
}
}