# Getting an empty list as output for {0},{0}. Please help . I couldn't find the bug.

• ``````/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:

//function to insert the node in output linked list
void insert(struct ListNode* temp)
{
struct ListNode *ptr=ret;
if(ptr==NULL)
{
ptr=temp;
return;
}
else
{
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=temp;
}

return;
}

{
int carry=0,temp_sum=0;
struct ListNode *head1=l1; //temp ptr to list1
struct ListNode   *head2=l2;//temp ptr to list2
struct ListNode *temp=NULL; //temp ptr to the answer list

{
temp=new ListNode(temp_sum%10);   //store last digit of sum
insert(temp);
carry=temp_sum/10;
}

while(head1!=NULL)// when linked list two gets over and one doesn't get over
{
temp=new ListNode(temp_sum%10);
insert(temp);
carry=temp_sum/10;
}

{
temp=new ListNode(temp_sum%10);
insert(temp);
carry=temp_sum/10;

}

if(carry)
{
temp=new ListNode(carry);
insert(temp);
}
return ret;
}
};``````

• You don't just have an error with {0},{0}. It will happen with every test where both numbers exist. Here is where you are making your mistake:

``````struct ListNode *ptr=ret;
if(ptr==NULL)
{
ptr=temp;
return;
}
``````

The line `*ptr = ret;` does exactly what it says. It makes the pointer ptr point to the same object as ret. ptr is null at the start, so it goes into the conditional, where `ptr=temp`. Unlike the last, this does something slightly different than you want. Instead of changing the memory location of ret to hold temp, it causes ptr to point to temp, while ret remains the same(null). The next time you run the function, the exact same thing will happen, leaving you with an empty list in every case.

To fix this, use:

``````struct ListNode *ptr=ret;
if(ptr==NULL)
{
ret=temp;
return;
}``````

• Please note I have not checked the rest of your program, so there may be other mistakes. The answer I gave was purely meant about the question you posed.

• Thank u so much :) GOT AC :) Perfect explanation.. This bug was torturing me for a long time

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.