本题解法思路简单,就是翻转后两个链表对应的数进行相加,如果得到结果大于10,则需要取余,并用一个数保留进位,但是该题边界条件判断较为复杂(俺都是各处取经)。
1、如果两个链表都没有到NULL则一直进行循环。其中如果在此循环中有一个链表已经为NULL,则不再访问这个链表val与Next,不然会段错误,所以需要一个变量来存储此链表的内容,此题设为
n1与n2.
2、如果两个链表都已经NULL但是最后相加得到的数大于10,那就还有余数,则需要再开辟一个空间来存储这个进位。
3、如上出现了条件判断(head1||head2||temp==1)
如果大佬们有改进地方欢迎指教俺。
truct ListNode* ReverseList(struct ListNode* pHead )//翻转链表
{
    struct ListNode*cur=pHead;
    struct ListNode*New=(struct ListNode*)malloc(sizeof(struct ListNode));
    New->next=pHead;
    while(cur!=NULL&&cur->next!=NULL)
    {
        struct ListNode*tail=cur->next;
        cur->next=tail->next;
        tail->next=New->next;
        New->next=tail;
    }
    return New->next;
}

struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
    int value=0,n1=0,n2=0;
    int temp=0;//进位数
    struct ListNode* New=(struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* copy=New;//设置一个变量保存New的地址因为后面New的指向会改变。
    New->next=NULL;
    
    head1=ReverseList(head1);
    head2=ReverseList(head2);
    while(head1||head2||temp==1)
    {
        n1=head1!=NULL?head1->val:0;
        n2=head2!=NULL?head2->val:0;
        
        value=temp+n1+n2;
        temp=0;
        temp=value/10;
        value%=10;
        struct ListNode* data=(struct ListNode*)malloc(sizeof(struct ListNode));
        data->val=value;
        data->next=NULL;
        New->next=data;
        New=data;
        
        head1=head1!=NULL?head1->next:NULL;
        head2=head2!=NULL?head2->next:NULL;               
        
    }
    return ReverseList(copy->next);
}