用两个栈实现队列

用两个栈实现队列

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

代码实现

package 剑指offer;

import java.util.Stack;

/**
 * @author WangXiaoeZhe
 * @Date: Created in 2019/11/22 15:07
 * @description:
 */

public class Main4 {
    public static void main(String[] args) {

    }

    Stack<Integer>stack1=new Stack<>();
    Stack<Integer>stack2=new Stack<>();
    /**
     * 将元素压倒栈1中
     */

    public void push(int node){
        stack1.push(node);
    }
    public int pop(){
        /**
         * 将栈1中的元素压倒栈2中
         */

        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
        /**
         * 第一次出队
         */

        int first = stack2.pop();
        /**
         * 然后再将栈2剩下的元素倒入到栈1中
         */

        while (!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }
        /**
         * 完成以此出队
         */

        return first;
    }
}
posted @ 2019-11-22 15:16  π。  阅读(143)  评论(0编辑  收藏  举报