用两个栈实现队列

来源:互联网 发布:js true false 转换 编辑:程序博客网 时间:2024/05/06 19:57

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

最佳答案:通过所有测试用例的代码:思路:有两个栈,栈1和栈2.当入栈的时候,我们将它全放进栈1中,当需要出栈的时候,我们将栈1出栈到栈2中,然后再将栈2依次出栈。所以入栈的时候,思路很简单,注意到要将int类型转为Integer类型,我们使用了new Integer(int);当需要出栈的时候,我们用API提供的方法while(stack1.isEmpty())来将所有栈1的元素压入栈2中,然后将栈2弹出就可以。这里又涉及到将Integer的类型转为int类型的方法Integer.intValue();实现代码如下:

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(new Integer(node));
    }
    
    public int pop() {
    if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop().intValue();
    }
}

0 0
原创粉丝点击