0

我目前正在为我的编程考试进行修改,我在过去的一篇论文中遇到了一个让我相当困惑的问题。

我有两个类,队列和节点,如下所示。

该问题指出,我必须通过将必要的代码添加到将存储在队列中的所有数据打印到控制台的 inspectQueue 方法中来扩展 Queue 类的行为。

我能想到的唯一解决方案,它非常弱,是有一个简单的 ArrayList 并且每次元素入队/出队时,然后将节点添加到列表中/从列表中删除节点。

我是否有更好的解决方案?我真的很感激一些指导。

我已经评论了我实现“解决方案”的代码,其余代码是它在试卷中的显示方式。

谢谢你的时间。

队列.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());
     }
}



}

节点.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;
}


}
4

4 回答 4

3

你的节点形成一个链表,所以就这样做

public void inspectQueue() {
    Node n = head;
    while (n != null) {
        System.out.println(n.getData());
        n = n.getNext();
    }
}
于 2013-04-04T12:54:34.607 回答
1

您不需要数组,您将这些信息存储在 Nodenext属性中:

public void inspectQueue() {
    Node current = head;
    while(current != null) {
        System.out.println(n.getData());
        current = current.getNext();
    }
}

该数据结构称为链表

于 2013-04-04T12:54:12.707 回答
1

这是一个非常基本的数据结构,称为 LinkedList。在 Node 类的代码中,您可以看到以下内容:

protected Node next;

这意味着每个节点还拥有对列表中下一个节点的引用。如果此 Node 是null,则列表中没有更多元素。知道了这一点,您可以像这样循环:

Node currentNode = this.head;
while(currentNode != null) {
    System.out.println(currentNode.getData().toString());
    currentNode = currentNode.getNext();
}

这消除了 ArrayList 来存储您的引用的需要。LinkedList 是一种非常常用的数据结构,理解起来非常重要。如果您有任何问题,请继续提问!

如果您还想要大小,请保留一个计数器,每次调用时递增它getNext(),并在 for 循环后打印大小。

于 2013-04-04T13:00:28.623 回答
0

更简单的解决方案是使用 开始queue.head并遍历节点的链表,并在进行过程中node.next打印数据。

于 2013-04-04T12:53:30.227 回答