今日算法06-用两个栈实现队列

一、题目描述

题目链接:leetcode.cn/problems/yo…

难易程度:简单

用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。

二、解题思路

通过下面两步来保持队列的先进先出特点:

  • in 栈用来处理入栈(push)操作,out 栈用来处理出栈(pop)操作。
  • 当元素要出栈时,需要先将 in 栈元素出栈,并进入 out 栈。

此时元素出栈顺序被反转,因此出栈顺序就和最开始入栈顺序是相同的,先进入的元素先退出,这就是队列的顺序。

复杂度分析

时间复杂度:

  • push() 函数为 O(1) ;
  • pop() 函数为 O(N) ;

空间复杂度 O(N) : 最差情况下,栈 A 和 B 共保存 N 个元素。

三、代码实现

 Stack<Integer> in = new Stack<Integer>();
 Stack<Integer> out = new Stack<Integer>();
 ​
 public void push(int node) {
     in.push(node);
 }
 ​
 public int pop() throws Exception {
     if (out.isEmpty())
         while (!in.isEmpty())
             out.push(in.pop());
 ​
     if (out.isEmpty())
         throw new Exception("queue is empty");
 ​
     return out.pop();
 }

推荐阅读

封面

今日算法系列,题解更新地址:studeyang.tech/2023/0720.h…

© 版权声明
THE END
喜欢就支持一下吧
点赞0

Warning: mysqli_query(): (HY000/3): Error writing file '/tmp/MY5yqx6r' (Errcode: 28 - No space left on device) in /www/wwwroot/583.cn/wp-includes/class-wpdb.php on line 2345
admin的头像-五八三
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

图形验证码
取消
昵称代码图片