僅用棧結構實現隊列結構


/**
 * @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();
    }
}



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