venkatraman hiregange
venkatraman hiregange

Reputation: 105

Facing a problem while reversing a linked list

I am trying to reverse linked list using java and written below code.

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur=head,prev=null,newHead=null;
        
        while(cur!=null)
        {
          newHead=cur;
          newHead.next=prev;
            prev=newHead;
            System.out.println(1);
            cur=cur.next;
    
        }
        
        return newHead;
        
        
    }
}

I am not understanding why the loop is executed only once here. Am i doing something wrong?

Upvotes: 0

Views: 17

Answers (1)

trincot
trincot

Reputation: 350242

This happens because you have altered cur.next with the assignment newHead.next=prev;, making it null. Realise that newHead references the same object as cur at that moment.

You should save the original value of cur.next before this change happens:

ListNode cur = head, prev = null, newHead = null, next;
    
while (cur != null)
{
    newHead = cur;
    next = cur.next; // <--- save original value of `cur.next`
    newHead.next = prev;
    prev = newHead;
    cur = next;  // <--- use that original value here
}

Upvotes: 2

Related Questions