僅用隊列結構實現棧結構

實現思路:

準備兩個隊列,push元素時將queue中除了最後一個元素依次poll出並push到輔助隊列中,這樣queue最後一個元素就是我們要pop的元素,然後我們交換queue和輔助隊列的引用方便複用。

代碼:

/**
 * @description:僅用隊列結構實現棧結構
 * @Author MRyan
 * @Date 2020/5/17 15:00
 * @Version 1.0
 */
public class QueueAchieveStack {
    //隊列
    public static Queue<Integer> queue;
    //輔助隊列
    public static Queue<Integer> help;

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

    /**
     * 初始化
     */
    public static void init() {
        queue = new LinkedList<>();
        help = new LinkedList<>();
    }

    /**
     * 壓棧
     *
     * @param nums
     */
    public static void push(int nums) {
        queue.add(nums);
    }

    /**
     * 彈出
     *
     * @return
     */
    public static int pop() {
        if (queue.isEmpty()) {
            throw new RuntimeException("stack is empty");
        }
        //queue中除了最後一個元素依次poll出並push到輔助隊列中
        while (queue.size() > 1) {
            help.add(queue.poll());
        }
        //queue中最後一個元素就是要pop的元素
        int answer = queue.poll();
        //交換queue和help的引用方便複用
        swap();
        return answer;

    }

    public static int peek() {
        if (queue.isEmpty()) {
            throw new RuntimeException("stack is empty");
        }
        while (queue.size() != 1) {
            help.add(queue.poll());
        }
        int answer = queue.poll();
        help.add(answer);
        swap();
        return answer;
    }

    /**
     * 交換隊列和輔助隊列引用 方便複用
     */
    public static void swap() {
        Queue<Integer> temp = queue;
        queue = help;
        help = temp;

    }
}


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