The problem is at the partition(), which would read a LinkedList node and compare the data value of that node with an input int number. the program throws NullPointerException at the compare statement node.data < x. I cannot figure it out, could anyone help me? Thanks a lot.
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();
}
}
Quite simply, you are checking if the value of node.data is less than x. As node.data is an Integer type, it could quite possibly be null, meaning that this statement will throw a NullPointer. You could remedy this with a check in your while statement: