#include <stdlib.h>#include<stdio.h>/** Definition for singly-linked list. * struct ListNode {* int val; * struct ListNode *next; *};*/structListNode {intVal; structListNode *next;};structlistnode* AddTwoNumbers (structlistnode* L1,structlistnode*L2) { intdebug =0; structlistnode* Cur1 =L1; structlistnode* CUR2 =L2; structlistnode* L3 =malloc(sizeof(structListNode)); L3->val =0; L3->next =NULL; structlistnode* tmp =L3; structlistnode* CUR3 =L3; intV1 =0, V2 =0, V3 =0; intcarry =0, first =1; while(Cur1! = NULL | | CUR2! =NULL) {V1= (Cur1 = = NULL?)0: cur1->val); V2= (Cur2 = = NULL?)0: cur2->val); V3= V1 +v2; if(Carry = =1) {v3+=1; Carry=0; } if(V3 >9) {Carry=1; V3-=Ten; } tmp=malloc(sizeof(structListNode)); TMP->val =v3; TMP->next =NULL; if(First = =1) {L3=tmp; CUR3=L3; First=0; if(Debug = =1) printf ("tmp->val =%d\n", tmp->val); } Else{CUR3->next =tmp; CUR3= cur3->Next; if(Debug = =1) printf ("tmp->val =%d\n", tmp->val); } if(Debug = =1) printf ("V1 =%d, V2 =%d, V3 =%d\n", V1, V2, v3); if(Cur1! = NULL) Cur1 = cur1->Next; if(CUR2! = NULL) Cur2 = cur2->Next; } if(Carry = =1) {tmp=malloc(sizeof(structListNode)); TMP->val =1; TMP->next =NULL; CUR3->next =tmp; Carry=0; } returnL3;}intMain () {structlistnode* L1 =malloc(sizeof(structListNode)); structlistnode* L2 =malloc(sizeof(structListNode)); structlistnode* L3 =malloc(sizeof(structListNode)); structlistnode* TMP1 =malloc(sizeof(structListNode)); structlistnode* TMP2 =malloc(sizeof(structListNode)); structlistnode* Tmp3 =malloc(sizeof(structListNode)); //tmp3->val = 3; //tmp3->next = NULL; //tmp2->val = 4; //tmp2->next = Tmp3; //tmp1->val = 2; //tmp1->next = TMP2;Tmp2->val =8; TMP2->next =NULL; TMP1->val =1; TMP1->next =TMP2; L1=TMP1; TMP1=malloc(sizeof(structListNode)); TMP2=malloc(sizeof(structListNode)); Tmp3=malloc(sizeof(structListNode)); //tmp3->val = 4; //tmp3->next = NULL; //tmp2->val = 6; //tmp2->next = Tmp3; //tmp1->val = 5; //tmp1->next = TMP2;Tmp1->val =0; TMP1->next =NULL; L2=TMP1; L3=addtwonumbers (L1, L2); printf ("%d", l3->val); while(L3->next! =NULL) {L3= l3->Next; printf ("- %d", l3->val); } printf ("\ n"); return 0;}
[Leetcode] 2. Add the Numbers