题目
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
1
2
3
4 输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]示例 2:
1
2
3
4 输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]提示:
1
2 1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
两个栈,一个栈用来接收入队元素,那么出队的时候需要先进先出,也就是栈底先出,于是移到另一个栈实现反向排列,此时出栈顺序与队列出队顺序相同。
- 入栈:放入栈
rev
; - 出栈:另一个栈
rrev
非空时,意味着这些元素都是按照出队顺序排列的;如果为空,就从rev
移动到rrev
。
1 | class CQueue { |
好有趣的一道题。