如何用棧實現一個隊列?

棧是先進後出,隊列是先進先出,所以兩個棧,一個接收數據,一個處理並返回數據,出來就是一個隊列,先進先出的形式了。

如圖所示:
在這裏插入圖片描述

代碼實現:

package com.revision.Stack;

import java.util.Queue;
import java.util.Stack;

class Test {


    public static void main(String[] args) {
        Stack2Queue stack2Queue = new Stack2Queue();
        stack2Queue.push(1);
        stack2Queue.push(2);
        stack2Queue.push(3);
        stack2Queue.pop();
        stack2Queue.push(4);
        stack2Queue.pop();
        stack2Queue.pop();
        stack2Queue.pop();
    }


}

public class Stack2Queue {
    //作爲入隊列
    Stack<Integer> stack1 = new Stack<>();
    //作爲出隊列
    Stack<Integer> stack2 = new Stack<>();

    public void push(int num) {
        //push時先看stack2中有無數據,有的話就先放回給stack1中
        while (!stack2.empty()) {
            stack1.push(stack2.peek());
            stack2.pop();
        }
        //無數據就把數值先放進stack1中
        stack1.push(num);
        System.out.println("入隊元素爲:" + num);
    }

    public int pop(){
        //出隊時要保證stack1爲空,否則順序出錯
        while(!stack1.empty()){
            stack2.push(stack1.peek());
            stack1.pop();
        }
        int tmp = stack2.peek();
        System.out.println("出隊元素爲:" + tmp);
        stack2.pop();
        return tmp;
    }

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