キューのチェーンテーブル実装(FIFO)

4586 ワード

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

/**
 * Created by ZYQ on 2016/7/26.
 *   FIFO(    )   
 */
public class Queue {
    private Node first; //          
    private Node last;  //          
    private int N;      //     

    //         
    private class Node{
        String string;
        Node next;
    }

    //         
    public boolean isEmpty() {
        return first == null;
    }

    //        
    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 queue = new Queue();

        //        ,      ,          String  
        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();
            }
        }

        //           
        System.out.println("The Queue:");
        int number = queue.size();
        while (number != 0) {
            System.out.print(queue.first.string + "");
            queue.first = queue.first.next;
            number--;
        }
    }
}