这道题其实我有点蒙,只看题干信息的话,回答这个问题不难,可是我搞不清楚测试数据的输入输出QAQ
思路
用两个栈来实现队列功能,栈可以逆转数据的顺序,两次逆转就会变回来。
准备两个栈,一个作为中间过渡栈,“入栈”;一个作为最终结果栈,“出栈”
时间复杂度为O(n)
空间复杂度为O(n)
class CQueue {
private Stack<Integer> in,out;
//初始化该队列
public CQueue() {
in = new Stack<Integer>();
out = new Stack<Integer>();
}
//把数据添加到“入栈”里去
public void appendTail(int value) {
in.push(value);
}
public int deleteHead() {
//如果“出栈”为空
if(out.isEmpty())
//将“入栈”里的数转到“出栈”里去
while(!in.isEmpty())
out.push(in.pop());
//判断,如果“出栈”为空,return -1; 如果“出栈”不为空,则出栈一个元素
return out.isEmpty()? -1:out.pop();
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/