链表的子字符串方法问题

时间:2017-04-25 04:27:26

标签: java linked-list compareto

如何让我的子串方法起作用?

我一直在这一行得到一个空指针异常:copy = copy.next = new Node(curr.data);

public LL substring(int startPosition) {

    if (startPosition < 0)
        throw new IndexOutOfBoundsException();

    LL substring = new LL();
    Node curr = first;
    for (int i = 0; i < startPosition; i++) {
        curr = curr.next;
    }
    Node copy = new Node(curr.data);
    substring.first = copy;

    while (curr != null && copy != null) {
        curr = curr.next;
        copy = copy.next = new Node(curr.data);
    }
    return substring;
}

1 个答案:

答案 0 :(得分:0)

public LL substring(int startPosition) {
    if (startPosition < 0)
        throw new IndexOutOfBoundsException();

    LL substring = new LL();
    Node curr = first;
    for (int i = 0; i < startPosition; i++) {
        if (curr == null) {
            throw new IndexOutOfBoundsException();
        }
        curr = curr.next;
    }
    Node prev = null;
    while (curr != null) {
        Node copy = new Node(curr.data);
        if (prev == null) {
            substring.first = copy;
        } else {
            prev.next = copy;
        }
        prev = copy;
        curr = curr.next;
    }
    return substring;
}