2016-02-25 58 views
0

當我運行我的驅動程序類時,我的列表不會初始化。這是啓動清單所必需的。初始化鏈表

public class SortedListReferenceBased implements ListInterface { 
    private Node head; 
    private int numItems; // number of items in list 

    public SortedListReferenceBased() 
    // creates an empty list 
    { 
     head = new Node(null); 
     numItems = 0; 

    } // end default constructor 

    public boolean isEmpty() 
    // Determines whether a list is empty 
    { 
     return true; 
    } // end isEmpty 

    public int size() 
    // Returns the number of items that are in a list 
    { 
     return numItems; 
    } // end size 

    public void removeAll() 
    // Removes all the items in the list 
    { 
     head = null; 
     numItems = 0; 

    } // end removeAll 

    public Object get(int index) throws ListIndexOutOfBoundsException 
    // Retrieves the item at position index of a sorted list, if 0 <= index < 
    // size(). 
    // The list is left unchanged by this operation. 
    // Throws an exception when index is out of range. 
    { 
     if (index < 0 || index >= numItems) { 
      throw new ListIndexOutOfBoundsException(index + " is an invalid index"); 
     } 
     return new Object(); 
    } 

    public void add(Object item) throws ListException 
    // Inserts item into its proper position in a sorted list 
    // Throws an exception if the item connot be placed on the list 
    { 
     try { 
      Node newNode = new Node(item); 
      if (head != null) { 
       int i = locateIndexToAdd(item); 
       if (i >= -1 && i <= numItems) { 
        add(i, item); 
       } 
      } else { 
       head = new Node(newNode); 
       Node curr = head.getNext(); 
       curr.setNext(null); 
       numItems++; 
      } 
     } catch (Exception e) { 
      throw new ListException("Add to List failed: " + e.toString()); 
     } 
    } 
} 
+0

「my list wont initialize」你是什麼意思?你怎麼看? – MartinS

+0

我有一個驅動程序類,當使用時應該在Node頭放置一個單詞,但它給我一個錯誤,說它停止在添加方法 – frenzy1272

+1

請發佈堆棧跟蹤 – nolexa

回答

0

這個問題似乎是你add方法的這一部分:

head = new Node(newNode); 
Node curr = head.getNext(); 
curr.setNext(null); 
numItems++; 

我承擔Nodenext變量被null所以head.getNext()回報nullcurr初始化。當你打電話給curr.setNext(null)時,你會得到一個NullPointerException。由於這添加了列表中的第一個條目,因此要將第一個元素的next設置爲null。 此外,您不必將newNode換成Node,因爲它已經是一個節點。

head = newNode; 
head.setNext(null); 
numItems++; 

但既然你null初始化反正你沒有做任何事情。

head = newNode; 
numItems++; 
+0

謝謝,我沒有看到我正在調用下一個節點。 – frenzy1272