仅用栈结构实现队列结构


/**
 * @description:仅用栈结构实现队列结构
 * @Author MRyan
 * @Date 2020/5/17 16:59
 * @Version 1.0
 */

/**
 * 实现思路 准备两个栈,压栈后将栈中元素弹出在压入辅助栈中就实现了队列结构
 * 辅助栈里有元素不可以在压入辅助栈,一次性导完
 */
public class StackAchieveQueue {
    private static Stack<Integer> stack;
    private static Stack<Integer> help;

    public static final void main(String[] args) {
        init();
        push(2);
        push(3);
        push(4);
        System.out.println("peek:" + peek());
        System.out.println("pop:" + pop());
        System.out.println("peek:" + peek());
        System.out.println("pop:" + pop());
        System.out.println("peek:" + peek());
    }

    public static void init() {
        stack = new Stack<>();
        help = new Stack<>();
    }

    public static void push(int num) {
        stack.push(num);
    }

    public static int pop() {
        if (stack.isEmpty() && help.isEmpty()) {
            throw new RuntimeException("the queue is empty");
        }
        //辅助栈里没有元素,并且栈中有元素,就将栈中元素弹出压入辅助栈,辅助栈pop的元素就是我们需要的
        if (help.isEmpty()) {
            while (!stack.isEmpty()) {
                help.push(stack.pop());
            }
        }
        return help.pop();
    }


    public static int peek() {
        if (stack.isEmpty() && help.isEmpty()) {
            throw new RuntimeException("the queue is empty");
        }
        if (help.isEmpty()) {
            while (!stack.isEmpty()) {
                help.push(stack.pop());
            }
        }
        return help.peek();
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章