难度

简单

思路

双栈实现

  • 从主栈依次 pop 到 副栈中,此时相当于链表反转,直接 pop 副栈即可,
  • 而新增的可以直接添加到主栈,此时删除、新增不受任何影响。
  • 虽然 删除 操作需要遍历集合,但是把时间成本均摊则为 _**O(1)**_

    1. class CQueue_3 {
    2. private LinkedList<Integer> normal;
    3. private LinkedList<Integer> temp;
    4. public CQueue_3() {
    5. normal = new LinkedList<>();
    6. temp = new LinkedList<>();
    7. }
    8. public void appendTail(int value) {
    9. normal.push(value);
    10. }
    11. public int deleteHead() {
    12. if (temp.isEmpty()) {
    13. while (!normal.isEmpty()) {
    14. temp.push(normal.pop());
    15. }
    16. }
    17. if (temp.isEmpty()) {
    18. return -1;
    19. } else {
    20. return temp.pop();
    21. }
    22. }
    23. }

    | 时间复杂度 | O(1) | | —- | —- | | 空间复杂度 | O(n) |

总结

  • 双栈组合可以轻易实现 队列 需求,其他使用一个栈也可以完成需求,不过时间复杂度很高。
  • 对于优化方面,一是频繁插入新节点的则使用 LinkedList 对象,底层使用 双向链表 存储数据,但相应地,需要消耗一定空间。