两个数之和
代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { int n1 = 0; int n2 = 0; int a1[100] = {'\0'}; int a2[100] = {'\0'}; int sum[100] = {'\0'}; int len1 = 0; int len2 = 0; int len3 = 0; int flag = 0; //计数 int k; struct ListNode* pTmp = l1; //初始化(用10占用) for(k = 0 ;k<100;k++) { a1[k] = 10; a2[k] = 10; } while(1) { if(pTmp->next == NULL) { a1[n1] = pTmp->val; break; } a1[n1] = pTmp->val; pTmp = pTmp->next; n1++; } pTmp = l2; while(1) { if(pTmp->next == NULL) { a2[n2] = pTmp->val; break; } a2[n2] = pTmp->val; pTmp = pTmp->next; n2++; } for(int j = 0;a1[j] != 10;j++) { printf("%d",a1[j]); len1++; } printf("\n"); for(int j = 0;a2[j] != 10;j++) { printf("%d",a2[j]); len2++; } printf("\n"); printf("%d",len1); printf("\n"); printf("%d",len2); printf("\n"); for(k = 0; k < ((len1>len2)?len1:len2) ;k++) { sum[k] = (a1[k] + a2[k] + flag)%10; if(a1[k] == 10 || a2[k] == 10) { if((a1[k] != 10 && a1[k] + flag >= 10) || (a2[k] != 10 && a2[k] + flag >= 10)) { flag = 1; printf("!"); } else { flag = 0; } } else { if(a1[k] + a2[k] + flag >= 10 && a1[k] < 10 && a2[k] < 10) { flag = 1; printf("@"); } else { flag = 0; } } len3++; } if(1 == flag) { sum[k] = flag; len3++; } for(int j = 0;j<len3;j++) { printf("%d",sum[j]); } struct ListNode* pHead = (struct ListNode*)malloc(sizeof(struct ListNode)); pHead->val = sum[0]; pHead->next = NULL; struct ListNode* pMynode = pHead; for(k = 1;k<len3;k++) { struct ListNode*pNext = (struct ListNode*)malloc(sizeof(struct ListNode)); pNext->val = sum[k]; pMynode->next = pNext; pNext->next = NULL; pMynode = pNext; } return pHead; }