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.
There is flaw in your reasoning. When you (first step)
You are changing the first reference to null (which is correct) but you loose any reference to the next pointer. Two lines later you
tempwas null soreversedLinkedListwill be null.You need to store the next pointer to the temporary variable before changing it.
But this is not causing an exception. Please post the complete code and the stack trace of the exception