我目前正在修改我的編程考試,並且遇到了一個過去的問題,這讓我頗爲困惑。檢查一個隊列以打印所有元素
我有兩個類Queue和Node,如下所示。
的問題指出,我通過將必要的代碼來打印到控制檯存儲在隊列中的所有數據的方法inspectQueue延長隊列類的行爲。
我能想到的唯一解決方案是非常微弱的,那就是擁有一個簡單的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;
}
}
感謝您的回答和附加說明。 – TEK 2013-04-04 13:40:27