隊(duì)列Queue的鏈表實(shí)現(xiàn)(FIFO)

實(shí)現(xiàn)FIFO(先進(jìn)先出)的隊(duì)列

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by ZYQ on 2016/7/26.
 * 實(shí)現(xiàn)FIFO(先進(jìn)先出)的隊(duì)列
 */
public class Queue<String> {
    private Node first; // 最早添加的結(jié)點(diǎn)連接
    private Node last;  // 最近添加的結(jié)點(diǎn)連接
    private int N;      // 元素?cái)?shù)量

    // 定義結(jié)點(diǎn)的嵌套類
    private class Node{
        String string;
        Node next;
    }

    // 判斷鏈表是否為空
    public boolean isEmpty() {
        return first == null;
    }

    // 統(tǒng)計(jì)鏈表結(jié)點(diǎn)數(shù)
    public int size() {
        return N;
    }

    // 向表尾添加元素
    public void enqueue(String s) {
        Node oldlast = last;
        last = new Node();
        last.string = s;
        last.next = null;
        if (isEmpty()) {
            first = last;
        } else {
            oldlast.next = last;
        }
        N++;
    }

    // 從表頭刪除元素
    public String dequeue() {
        String s = first.string;
        first = first.next;
        if (isEmpty()) {
            last = null;
        }
        N--;
        return s;
    }

    // 測試用例
    public static void main(java.lang.String[] args ) throws IOException {

        Queue<java.lang.String> queue = new Queue<java.lang.String>();

        // 創(chuàng)建輸入流對象,讀取一行數(shù)據(jù),并以空格為分隔轉(zhuǎn)化為String數(shù)組
        System.out.println("Enter the statement:");
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        java.lang.String intput = reader.readLine();
        java.lang.String[] item = intput.split(" ");
        for (java.lang.String s : item) {
            // 輸入"-"代表出列,非"-"則入列
            if (!s.equals("-")) {
                queue.enqueue(s);
            } else if (!queue.isEmpty()) {
                System.out.println(queue.first.string + " left on queue");
                queue.dequeue();
            }
        }

        // 遍歷鏈表輸入隊(duì)列的值
        System.out.println("The Queue:");
        int number = queue.size();
        while (number != 0) {
            System.out.print(queue.first.string + "");
            queue.first = queue.first.next;
            number--;
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容