2012-10-29 169 views
-2

我正在處理涉及鏈接列表的作業分配。我們必須實現一個隊列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 + "]"; 
     } 

    } 

} 

如果有人可以幫助我走出這個我會很感激。謝謝你的時間! :)

+1

你有'enqueue()'方法。現在有什麼問題呢?而且請做得更具體,而不是「它不工作」。 –

+0

它拋出一個java.lang.NullPointerException異常 – salxander

+0

@Xander - 對,因爲你沒有檢查是否是你添加的*第一個*東西。 'tail'爲空。您需要處理添加第一個項目的情況(然後在這種情況下也設置「head」) –

回答

1

您不處理列表爲空的情況。您正在添加第一個項目,tailnull,您將得到適當的例外。

在嘗試使用它之前,您需要檢查tail以查看它是否爲null,如果情況正確,請採取相應措施。不要忘記設置head

1

你不需要這一行,下一個應該已經是null。

newElement.next = null; 

你也忘了在你排隊後增加sz。

如果您嘗試併入隊到一個空的鏈表會發生什麼?你將不得不處理這種情況,這就是爲什麼你會得到一個NullPointerException

0

您的排隊方法試圖設置tail.nextnewElement。如果尾巴尚未初始化,會發生什麼情況?你會得到一個NullPointerException。

1
public void enqueue(T newEntry) { 
     Node newElement = new Node(newEntry); 
     newElement.next = null; 
     if(tail != null) 
     { 
     tail.next = newElement; 
     tail = newElement; 

     }else 
     { 
     head=tail=newElement; 
     } 
    } 

檢查尾部是否爲空。如果tail爲空,則表示這是第一個節點。將此添加爲第一個節點。如尾巴後添加。