初始化链表

时间:2016-02-25 23:48:25

标签: java list

当我运行我的驱动程序类时,我的列表不会初始化。这是开始列表所必需的。

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());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题似乎是add方法的这一部分:

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

我假设next中的Node变量已使用null初始化,因此head.getNext()会为null返回curr。当您拨打curr.setNext(null)时,您会收到NullPointerException。由于这会在列表中添加第一个条目,因此您需要将第一个元素的next设置为null。 此外,您不必将newNode包裹在Node中,因为它已经是一个节点。

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

但是,无论如何你用null初始化它都不需要做任何事情。

head = newNode;
numItems++;