I have debugged and try to figure out the cause from stacktrace but unable to find the reason of NullPointerException for this particular input. If I change the last input(marked in code) greater than 20, code executes successfully, but if its less than 20 then it throws exception.
package geeksforgeek.examples.sorting;
public class SinglyLinkedList {
Node head;
Node current;
public void add(int data){
if(head == null){
head = new Node(data);
current = head;
return;
}
while(current.next != null)
current = current.next;
current.next = new Node(data);
}
public void print(Node node){
current = node;
while(this.current != null) {
System.out.print(" "+current.data);
current = current.next;
}
System.out.println();
}
static class Node {
int data;
Node next;
Node(int data){
this.data = data;
this.next = null;
}
}
public static void main(String[] args) {
SinglyLinkedList quick = new SinglyLinkedList();
quick.add(30);
quick.add(3);
quick.add(4);
quick.add(20);
quick.add(15);
quick.add(55);
quick.add(35);
quick.add(65);
quick.add(25);
quick.add(95);
quick.add(85);
quick.add(75);
quick.add(2); /*issue with 2, less than 20 throw exception*/
Node node = quick.head;
while (node.next != null)
node = node.next;
quick.print(quick.head);
sort(quick.head, node);
quick.print(quick.head);
}
public static void sort(Node low, Node high){
if(low==high)
return;
Node prePivot = partition(low,high);
sort(low,prePivot);
if(low != null && prePivot==low){
sort(prePivot.next,high);
}else if(prePivot != null && prePivot.next != null){
sort(prePivot.next.next, high);
}
}
public static Node partition(Node low, Node high){
if(low == high || low == null || high == null)
return low;
Node prePivot = low;
Node current = low;
Node pivot = high;
while(low != high) {
if (low.data < pivot.data) {
prePivot = current;
int temp = current.data;
current.data = low.data;
low.data = temp;
current = current.next;
}
low = low.next;
}
int temp = current.data;
current.data = pivot.data;
pivot.data = temp;
return prePivot;
}
}
Exception in thread "main" java.lang.NullPointerException at geeksforgeek.examples.sorting.SinglyLinkedList.partition(SinglyLinkedList.java:86) at geeksforgeek.examples.sorting.SinglyLinkedList.sort(SinglyLinkedList.java:67) at geeksforgeek.examples.sorting.SinglyLinkedList.sort(SinglyLinkedList.java:72) at geeksforgeek.examples.sorting.SinglyLinkedList.sort(SinglyLinkedList.java:68) at geeksforgeek.examples.sorting.SinglyLinkedList.sort(SinglyLinkedList.java:70) at geeksforgeek.examples.sorting.SinglyLinkedList.main(SinglyLinkedList.java:59)