0

How do I get my substring method to work?

I keep getting a null pointer exception on this line: 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;
}
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
nerdcode
  • 11
  • 2

1 Answers1

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;
}
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24