Bootstrap

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

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

语言:Java
运行时间:10ms
占用内存:9428k
难度1星

解题思路及代码如下:

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    /*
    每次直接入栈,
    弹栈先将数据逆序输出到另外一个栈,然后输出栈顶,
    算法描述:
    入栈时,直接入到stack1
    出栈时:
    首先判断stack2是否为空,如果为空,就将stack1中的元素放到stack2中
    若是不为空,就直接弹出栈顶
    
    */
    public void push(int node) {
        //队列:先进先出
         stack1.push(node);   
    }
    //出栈         
    public int pop() {
        if(stack1.empty() && stack2.empty()){
            throw new RuntimeException("Stack is empty");
        }
        
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }    
        }
        
       
        return stack2.pop();
    }
}
;