我正在處理涉及鏈接列表的作業分配。我們必須實現一個隊列ADT,並且我遇到的一個方法是將一個節點添加到列表的末尾(enqueue方法)。這裏是我的代碼:將節點添加到Java中鏈接列表的末尾
公共類隊列實現QueueInterface {
private Node head;
private Node tail;
private int sz;
public Queue() {
head = null;
tail = null;
sz = 0;
}
public void enqueue(T newEntry) {
Node newElement = new Node(newEntry);
newElement.next = null;
tail.next = newElement;
tail = newElement;
}
public T dequeue() {
T result = null;
if(head != null) {
result = head.data;
head = head.next;
sz--;
}
return result;
}
public T getFront() {
return head.data;
}
public boolean isEmpty() {
if (head == null) {
return true;
}
return false;
}
public void clear() {
while (!isEmpty()) {
dequeue();
}
}
@Override
public String toString() {
return "Queue [head=" + head + ", sz=" + sz + "]";
}
public class Node {
private Node next;
private T data;
public Node (T newData) {
data = newData;
}
@Override
public String toString() {
return "Node [next=" + next + ", data=" + data + "]";
}
}
}
如果有人可以幫助我走出這個我會很感激。謝謝你的時間! :)
你有'enqueue()'方法。現在有什麼問題呢?而且請做得更具體,而不是「它不工作」。 –
它拋出一個java.lang.NullPointerException異常 – salxander
@Xander - 對,因爲你沒有檢查是否是你添加的*第一個*東西。 'tail'爲空。您需要處理添加第一個項目的情況(然後在這種情況下也設置「head」) –