Pass by reference for Linked List
Anonymous User
149

Following is my code for reversing a linked list, why does pass by reference ListNode* reverse(ListNode*& cur, ListNode*& nxt) not work, i understand why pass by value works ListNode* reverse(ListNode* cur, ListNode* nxt)
Guys ,please help me in understanding this.
Thanks

class Solution {
public:
    ListNode* reverse(ListNode*& cur, ListNode*& nxt){  
        if(nxt->next==NULL){
           // if(nxt==0) cout << "nxt is null";
           // if(cur==0) cout << "cur is null";
           // cout << cur->val << " " << nxt->val << endl;
            nxt->next = cur;
            cur->next = NULL;
          //  if(nxt==0) cout << "nxt is null";
          //  if(cur==0) cout << "cur is null";
            cout << cur->val << " " << nxt->val << endl;
            return nxt;
        }
        
        ListNode* head = reverse(cur->next, nxt->next);
        nxt->next = cur;
        cur->next= NULL;    
        
        return head;
    }
    ListNode* reverseList(ListNode* head) {
        if(head==0) return NULL;
        if(head->next==0) return head;
        return reverse(head,head->next);
    }
};
Comments (0)