私は現在、プログラミング試験の修正を行っていますが、過去の論文からかなり混乱している質問に出くわしました。
以下に示すように、Queue と Node の 2 つのクラスがあります。
この質問は、キュー内に保存されているすべてのデータをコンソールに出力する必要なコードを inspectQueue メソッドに追加することによって、Queue クラスの動作を拡張する必要があることを示しています。
私が考えることができる唯一の解決策は、非常に弱いですが、単純なArrayListを持ち、要素がキューに入れられたりキューから取り出されたりするたびに、ノードをリストに追加/リストから削除することです。
私が見落としているより良い解決策はありますか?アドバイスをいただければ幸いです。
「解決策」を実装したコードにコメントしました。残りのコードは、試験用紙にどのように表示されるかです。
御時間ありがとうございます。
Queue.java
public class Queue {
protected Node head;
protected Node last;
    //added by me
    private ArrayList<Node> nodes = new ArrayList<Node>();
    //end my add
public boolean isEmpty() {
    return (this.head == null);
}
public void enqueue(Object d) {
    Node n = new Node();
    n.setData(d);
    nodes.add(n); //added by me
    if (this.isEmpty()) {
        head = n;
        last = n;
    }
    else {
        last.setNext(n);
        last = n;
    }
}
public Object dequeue() {
    if(this.isEmpty()) {
        this.last = null;
        return null;
    }
    else {
        Node h = this.head;
                    nodes.remove(h); //added by me
        head = h.getNext();
        return h.getData();
    }
}
public Object peek() {
    if(this.isEmpty()) {
        return null;
    }
    else {
        Node t = this.head;
        return t.getData();
    }
}
public void clearQueue() {
    this.head = null;
    this.last = null;
}
public void inspectQueue() {
         //added by me (all below)
     System.out.println("Inspecting Queue: (contains " + nodes.size() + " nodes)");
     for(Node n : nodes) {
      System.out.println(n.getData());
     }
}
}
Node.java
public class Node  {
protected Object data;
protected Node next;
public void setNext(Node e) {
    this.next = e;
}
public Node getNext() {
    return this.next;
}
public void setData(Object d) {
    this.data = d;
}
public Object getData() {
    return this.data;
}
}