🌕 剑指 Offer 09. 用两个栈实现队列
2022年10月10日
- algorithm
🌕 剑指 Offer 09. 用两个栈实现队列
难度: 🌕
问题描述
解法
class CQueue {
// 思路:
// 双栈,一个作为辅助栈
LinkedList<Integer> stack;
LinkedList<Integer> ts;
public CQueue() {
stack = new LinkedList<>();
ts = new LinkedList<>();
}
public void appendTail(int value) {
stack.push(value);
}
public int deleteHead() {
// 将 stack 的全部元素压入 ts
int res = -1;
if(!ts.isEmpty()) {
return ts.pop();
}
// ts.isEmpty()
if(stack.isEmpty()) {
return res;
}
// 将 stack 的元素全部压入 ts
while(!stack.isEmpty()) {
ts.push(stack.pop());
}
res = ts.pop();
return res;
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/