第一个栈:用来实现appendTail(),先进的被压在下面,不就相当于位于队列的队头嘛,最上面的于元素不就相当于队尾嘛。
第二个栈:用来实现deleteHead(),当stack2为空时,且当stack1不为空时,利用栈先进后出的性质,将stack1中的元素是全部挪到stack2中,那么对头就移到了栈顶,直接pop()即实现了删除队头元素。若stack2为空,且stack1也为空,则说明队列中没有元素,返回-1即可。
class CQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
public CQueue() {
stack1 = new Stack();
stack2 = new Stack();
}
public void appendTail(int value) {
stack1.push(value);
}
public int deleteHead() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.isEmpty() ? -1 : stack2.pop();
}
}