剑指Offer系列_09_用两个栈实现队列
package leetcode.sword_to_offfer.day01;
import java.util.LinkedList;
/**
* 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,
* 分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead操作返回 -1 )
* <p>
* 示例 1:
* <p>
* 输入:
* ["CQueue","appendTail","deleteHead","deleteHead"]
* [[],[3],[],[]]
* 输出:[null,null,3,-1]
* 示例 2:
* <p>
* 输入:
* ["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
* [[],[],[5],[2],[],[]]
* 输出:[null,-1,null,null,5,2]
* <p>
* <p>
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*
* @author soberw
* @Classname CQueue
* @Description
* @Date 2022-02-07 8:34
*/
public class CQueue {
private final LinkedList<Integer> list;
private final LinkedList<Integer> listOut;
public CQueue() {
list = new LinkedList<>();
listOut = new LinkedList<>();
listOut.add(null);
}
public void appendTail(int value) {
list.add(value);
listOut.add(null);
}
public int deleteHead() {
if (list.isEmpty()) {
listOut.add(-1);
listOut.pop();
return -1;
}
Integer removeFirst = list.removeFirst();
listOut.add(removeFirst);
return removeFirst;
}
}