0

I have the following code to reverse linked list But I am getting NPE at head.next = prev; How can I resolve it?

    ListNode l = new ListNode();
            l.insert(4);
            l.insert(10);
            l.insert(12);

            l.show();
            l.reverse();
            l.show();

public void reverse() {
        ListNode nextNode = null;
        ListNode curr = head;
        ListNode prev = null;

        while (curr != null) {

            nextNode = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextNode;
        }

        head = curr;
        head.next = prev;

    }
Raj R
  • 63
  • 1
  • 3
  • 11

2 Answers2

0

you're checking for curr to be null or not while you should check for curr.next to be null or not.

Ali Ben Zarrouk
  • 1,891
  • 16
  • 24
0

I am on mobile but what I see in the first go is...

head = curr; is out of while loop which means null will also be added to head and in next line

head.next = prev; we have an operation performed with 'dot'. That would lead to failure I feel.

is it the only issue??

Kunal Vohra
  • 2,703
  • 2
  • 15
  • 33