如何让我的子串方法起作用?
我一直在这一行得到一个空指针异常: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;
}
答案 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;
}