题干:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
题解:先定义两个栈作为成员变量,第一个栈sin用来入队,第二个栈sout用来出队。加入成员就直接push进sin,删除的话就要先把sin栈中的元素存到sout栈中,sin就相当于把sout翻转了,然后peek查找栈顶元素,记录下来并删除。接下来再把sout中的元素放回到sin里,就删除完成了。
class CQueue {
public Stack<Integer> sin;
public Stack<Integer> sout;
public CQueue() {
sin = new Stack<Integer>();
sout = new Stack<Integer>();
}
public void appendTail(int value) {
sin.push(value);
}
public int deleteHead() {
int x,result=-1;
while(sin.isEmpty()){
return -1;
}
while(!sin.isEmpty()){
x = sin.peek();
sin.pop();
sout.push(x);
}
result = sout.peek();
sout.pop();
while(!sout.isEmpty()){
x = sout.peek();
sout.pop();
sin.push(x);
}
return result;
}
}