I am writing a Java function to reverse a linked list in-place. I am new to Java and fail to be successfully debug the bug in the function below. The IDE returns a NullPointerException that I can't seem to figure out. Any help would be much appreciated.
public listNode reverseLinkedList(listNode head)
{
listNode reversedLinkedList = head;
listNode temp = null;
while (reversedLinkedList != null) {
reversedLinkedList.setNext(temp);
temp = reversedLinkedList;
reversedLinkedList = reversedLinkedList.getNext();
}
return reversedLinkedList;
}
For testing, I have a linked list intialized already with 8 linked nodes. In the function above, I am trying to swap the next pointers between each nodes and move reversedLinkedList
pointer along the linked list.
EDIT: Some have suggested that I use debugger to identify where the NullPointerException
occurs. I already did that. It occurs in the line reversedLinkedList = reversedLinkedList.getNext();
in the second iteration of the while
loop.
I initialized the linked list with 8 pointers for testing. The while
loop, instead of going to the second node, instead sees a null
pointer. It may have something to do with the temp variable but I am not sure.