Java实现用两个栈来实现队列

来源:互联网 发布:java api1.7中文版 编辑:程序博客网 时间:2024/04/29 09:57

题目描述

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

我的思路就是,栈1用来pop,栈2用来push。

所以栈1pop之前,应该保证pop的数是最早入栈的数。栈2push之前要保证先于该数的所有数已经都在栈2里面了。


这是一次AC的代码,41ms ,528K

import java.util.Stack;public class Solution {    Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();        public void push(int node) {        while(!stack1.isEmpty()){            stack2.push(stack1.pop());        }        stack2.push(node);    }        public int pop() {    while(!stack2.isEmpty()){            stack1.push(stack2.pop());        }                return stack1.pop();    }}

看一下评论区大神的代码:

链接:https://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6来源:牛客网import java.util.Stack; public class Solution {    Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();         public void push(int node) {        stack1.push(node);    }         public int pop() {        if(stack1.empty()&&stack2.empty()){            throw new RuntimeException("Queue is empty!");        }        if(stack2.empty()){            while(!stack1.empty()){                stack2.push(stack1.pop());            }        }        return stack2.pop();    }}


嗯。确实。

我应该考虑一下边界条件的,栈为空,或者不是int类型的输入等等。