【追求进步】用两个栈实现队列

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
在线代码:
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));//先将元素压入栈1
    }
    
    public int pop() {
       if(stack2.empty()){
           while(!stack1.empty()){
               stack2.push(stack1.pop());//将栈1元素压入栈2
           }
       }
        if(stack1.empty()){
            System.out.println("stack1 is empty");
        }
        return stack2.pop().intValue();//将栈2元素出栈的形式就是队列
    }
}


你可能感兴趣的:(【追求进步】用两个栈实现队列)