2021/3/14 剑指 Offer 09. 用两个栈实现队列
用两个栈实现队列
https://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6
题目描述
https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/submissions/
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 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]
解题思路
- 队列是 FIFO,而栈是 FILO。那么两个 FILO结合起来就能实现FIFO。栈 A 和栈 B 两个栈,A 用来接收新增元素,B 用来接收来自 A 弹栈的元素,在栈 B 中弹出一个元素后,再返还给栈 A,实现队列 FIFO 的效果。
- 如果按照(1)中所说的,B 弹完栈后从栈 B 中返还给 A,效率很低,所以应该继续保留在 B 中,直至 B 弹空为止,再将 A 的元素给 B。
Java实现代码
class CQueue { private Stack<Integer> stack1; private Stack<Integer> stack2; public CQueue() { stack1 = new Stack<>(); stack2 = new Stack<>(); } public void appendTail(int value) { stack1.push(value); } public int deleteHead() { int value = -1; if (!stack2.empty()) { return stack2.pop(); } if (stack1.empty()) return -1; while (!stack1.empty()) { stack2.push(stack1.pop()); } return stack2.pop(); } } /** * Your CQueue object will be instantiated and called as such: * CQueue obj = new CQueue(); * obj.appendTail(value); * int param_2 = obj.deleteHead(); */