#include<stdio.h>#include<stdlib.h>#include<string.h>#include"list.h"structListNode{intval;structListNode*next;};/* * [in] * @nd1: linked list of nodes * @nd2: linked list of nodes * * [out] * none * * [in/out] * @carry(in): carry value of last sum * @carry(out): carry value of current sum */staticstructListNode*addTwoNodes(structListNode*nd1,structListNode*nd2,int*carry){structListNode*nd_sum=malloc(sizeof(structListNode));if(!nd_sum){printf("malloc node failed\n");returnNULL;}nd_sum->val=0;nd_sum->next=NULL;nd_sum->val=(nd1->val+nd2->val+*carry)%10;*carry=(nd1->val+nd2->val+*carry)/10;returnnd_sum;}structListNode*addTwoNumbers(structListNode*l1,structListNode*l2){structListNode*nd1=l1;structListNode*nd2=l2;structListNode*nd_cont=NULL;structListNodend_zero={0,NULL};structListNode*l_head=NULL;structListNode*l_tail=l_head;structListNode*nd_sum=NULL;intcarry=0;while(nd1&&nd2){nd_sum=addTwoNodes(nd1,nd2,&carry);if(!nd_sum)returnNULL;if(!l_head){/* empty list */l_tail=l_head=nd_sum;}else{/* l_tail keeps track of the last node of list */l_tail->next=nd_sum;l_tail=nd_sum;}nd1=nd1->next;nd2=nd2->next;}if(!nd1&&!nd2){gotocarry;}elseif(nd1&&!nd2){nd_cont=nd1;}else{/* !nd1 && nd2 */nd_cont=nd2;}while(nd_cont){nd_sum=addTwoNodes(nd_cont,&nd_zero,&carry);if(!nd_sum)returnNULL;if(!l_head){/* in case one of the two lists is initially empty */l_tail=l_head=nd_sum;}else{l_tail->next=nd_sum;l_tail=nd_sum;}nd_cont=nd_cont->next;}carry:if(carry){nd_sum=malloc(sizeof(structListNode));if(!nd_sum)returnNULL;nd_sum->val=carry;nd_sum->next=NULL;l_tail->next=nd_sum;l_tail=nd_sum;}returnl_head;}