我目前正在修改我的编程考试,我发现了一篇过去的论文中的一个问题让我很困惑。
我有两个类,Queue和Node,如下所示。
问题表明我必须通过向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;
}
}
答案 0 :(得分:3)
您的节点形成链接列表,所以只需执行
public void inspectQueue() {
Node n = head;
while (n != null) {
System.out.println(n.getData());
n = n.getNext();
}
}
答案 1 :(得分:1)
您不需要数组,您将该信息存储在Node next
属性中:
public void inspectQueue() {
Node current = head;
while(current != null) {
System.out.println(n.getData());
current = current.getNext();
}
}
该数据结构称为linked list。
答案 2 :(得分:1)
这是一个非常基本的数据结构,称为LinkedList。在Node类的代码中,您可以看到以下内容:
protected Node next;
这意味着每个节点还包含对列表中下一个节点的引用。如果此节点为null
,则列表中不再包含任何元素。知道了这一点,你可以像这样循环:
Node currentNode = this.head;
while(currentNode != null) {
System.out.println(currentNode.getData().toString());
currentNode = currentNode.getNext();
}
这消除了ArrayList存储引用的需要。 LinkedList是一种非常常用的数据结构,非常重要。如果您有任何疑问,请继续问问!
如果您还想拥有尺寸,请保持计数器,每次调用getNext()
时递增计数器,并在for循环后打印尺寸。
答案 3 :(得分:0)
更简单的解决方案是从queue.head
开始并使用node.next
遍历链接的节点列表,随时打印数据。