/**
* Definition for singlylinked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
struct ListNode *ret=NULL; //ptr to head of linked list returned finally
//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;
}
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
{
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
while(head1!=NULL && head2!=NULL) //while there are 2 linked lists
{
temp_sum=head1>val + head2>val + carry;
temp=new ListNode(temp_sum%10); //store last digit of sum
insert(temp);
carry=temp_sum/10;
head1=head1>next;
head2=head2>next;
}
while(head1!=NULL)// when linked list two gets over and one doesn't get over
{
temp_sum=head1>val + carry;
temp=new ListNode(temp_sum%10);
insert(temp);
carry=temp_sum/10;
head1=head1>next;
}
while(head2!=NULL)
{
temp_sum=head2>val + carry;
temp=new ListNode(temp_sum%10);
insert(temp);
carry=temp_sum/10;
head2=head2>next;
}
if(carry)
{
temp=new ListNode(carry);
insert(temp);
}
return ret;
}
};
Getting an empty list as output for {0},{0}. Please help . I couldn't find the bug.


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, whereptr=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; }