用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
示例 2:
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
提示:
1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用
解题思路
解法:
1.用两个栈,pushStack用于模拟入队操作,每次入队,加入pushStack即可
2.popStack用于模拟出队操作,每次出队,将pushStack中所有元素出栈,入到popStack里面,然后popStack栈底元素即为所求元素
3.别忘记,还原pushStack,即将popStack栈元素一一出栈,入栈到pushStack即可
解题遇到的问题
无
后续需要总结学习的知识点
无
##解法1
import java.util.Stack;
class CQueue {
Stack<Integer> popStack = null;
Stack<Integer> pushStack = null;
public CQueue() {
popStack = new Stack<Integer>();
pushStack = new Stack<Integer>();
}
public void appendTail(int value) {
pushStack.push(value);
}
public int deleteHead() {
popStack.clear();
while (!pushStack.isEmpty()) {
popStack.push(pushStack.pop());
}
int ans = -1;
boolean flag = true;
while (!popStack.isEmpty()) {
if (flag) {
ans = popStack.pop();
flag = false;
} else {
pushStack.push(popStack.pop());
}
}
return ans;
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/