加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

【剑指OFFER】用两个栈实现队列

发布时间:2020-12-15 07:42:17 所属栏目:Java 来源:网络整理
导读:【问题描述】 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。 时间限制:1秒?空间限制:32768K ? 【AC代码】 1 import java.util.Stack; 2 3 public class Solution { 4 StackInteger stack1 = new StackInteger (); 5 StackIn

【问题描述】

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

时间限制:1秒?空间限制:32768K

?

【AC代码】

 1 import java.util.Stack;
 2 
 3 public class Solution {
 4     Stack<Integer> stack1 = new Stack<Integer>();
 5     Stack<Integer> stack2 = new Stack<Integer>();
 6     
 7     public void push(int node) {
 8         stack1.push(node);
 9     }
10     
11     public int pop() {
12         if (stack2.isEmpty()) {
13             while (!stack1.isEmpty()) {
14                 stack2.push(stack1.pop());
15             }
16         }
17         return stack2.pop();
18     }
19 }
View Code

Reference:?https://blog.nowcoder.net/n/ee03f62d5a6e4b5ea571d61ad7eb64c8?f=comment

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读