剑指 Offer 09. 用两个栈实现队列

1. Question

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTaildeleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

2. Examples

示例 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]

3. Constraints

  • 1 <= values <= 10000
  • 最多会对 appendTail、deleteHead 进行 10000 次调用

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

class CQueue {

  Deque<Integer> input;
  Deque<Integer> output;

  public CQueue() {
    input = new ArrayDeque<>();
    output = new ArrayDeque<>();
  }

  public void appendTail(int value) {
    while (!output.isEmpty()) {
      input.push(output.pop());
    }
    input.push(value);

  }

  public int deleteHead() {
    while(!input.isEmpty()) {
      output.push(input.pop());
    }
    return output.isEmpty() ? -1 : output.pop();
  }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2022-11-26 20:03:31

results matching ""

    No results matching ""