Jump to content

Reverse a linked list in Java


shriyanshi

Recommended Posts

Hi everyone,

I am trying to reverse a linked list in Java. I am following the algorithm from the blog post program to reverse a linked list, but I am getting an error.

Here is my code

public class ReverseLinkedList {

    public static Node reverse(Node head) {
        Node prev = null;
        Node curr = head;
        Node next = null;

        while (curr != null) {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }

        return prev;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);

        Node reversedHead = reverse(head);

        System.out.println(reversedHead.data); // 4
        System.out.println(reversedHead.next.data); // 3
        System.out.println(reversedHead.next.next.data); // 2
        System.out.println(reversedHead.next.next.next.data); // 1
    }
}

My error:

Exception in thread "main" java.lang.NullPointerException
at ReverseLinkedList.reverse(ReverseLinkedList.java:24)
at ReverseLinkedList.main(ReverseLinkedList.java:34)

I am not sure where the NullPointerException is coming from. Can somebody assist me with debugging this code?

Thanks!
 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...