2017-04-25 68 views
0

如何讓我的子串方法工作?鏈接列表子串方法問題

我不斷收到這條線上空指針異常: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

'curr.next'可能是'null',所以有一個NLP在'curr.data' – Oswald

回答

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