问题在于partition()
,它将读取一个LinkedList
节点并将该节点的数据值与输入的 int 数进行比较。程序抛出NullPointerException
比较语句node.data < x
。我无法弄清楚,有人可以帮助我吗?非常感谢。
package Chapter2;
import java.util.*;
public class LinkedList2<E>{
static class LinkedListNode<E>{
E data;
LinkedListNode<E> next;
}
private LinkedListNode<E> head;
private LinkedListNode<E> tail;
public LinkedList2(){
this.head = new LinkedListNode<E>();
this.tail = new LinkedListNode<E>();
head.next = tail;
}
public void addLast(E e){
LinkedListNode<E> node = new LinkedListNode<E>();
tail.data = e;
tail.next = node;
tail = node;
}
public void print(){
LinkedListNode<E> curr = head.next;
while(curr.next != null){
System.out.print(curr.data + " ");
curr = curr.next;
}
System.out.println("");
}
public LinkedListNode<Integer> partition(LinkedListNode<Integer> node, Integer x){
LinkedListNode<Integer> beforeStart = null;
LinkedListNode<Integer> beforeEnd = null;
LinkedListNode<Integer> afterStart = null;
LinkedListNode<Integer> afterEnd = null;
while(node!= null){
LinkedListNode<Integer> next = node.next;
node.next = null;
System.out.println(node.data);
if(node.data < x){
if(beforeStart == null){
beforeStart = node;
beforeEnd = beforeStart;
}else{
beforeEnd.next = node;
beforeEnd = node;
}
}else{
if(afterStart == null){
afterStart = node;
afterEnd = afterStart;
}else{
afterEnd.next = node;
afterEnd = node;
}
}
node = next;
}
if(beforeStart == null){
return afterStart;
}
beforeEnd.next = afterStart;
return beforeStart;
}
public static void main(String[] args){
LinkedList2<Integer> listInt = new LinkedList2<Integer>();
listInt.addLast(5);
listInt.addLast(8);
listInt.addLast(1);
listInt.addLast(3);
listInt.addLast(6);
listInt.print();
System.out.println(listInt.head.next.data);
listInt.partition(listInt.head.next, 4);
listInt.print();
}
}