# Leetcode 2. Add Two Numbers (C語言) - 題目 You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. - 範例 Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. ```c struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){ if(!l1)return l2; if(!l2)return l1; struct ListNode *root,*current,*Nnode; current=(struct ListNode*)malloc(sizeof(struct ListNode)); root=current; int v1,v2,carry=0,temp; while(l1||l2){ v1=l1?l1->val:0; v2=l2?l2->val:0; temp=v1+v2+carry; if(temp>9){ temp%=10; carry=1; } else{ carry=0; } Nnode=(struct ListNode*)malloc(sizeof(struct ListNode)); Nnode->val=temp; current->next=Nnode; current=current->next; if(l1)l1=l1->next; if(l2)l2=l2->next; } if(carry==1){ Nnode=(struct ListNode*)malloc(sizeof(struct ListNode)); Nnode->val=1; Nnode->next=NULL; current->next=Nnode; } Nnode->next=NULL; current=root->next; free(root); return current; } ``` 思路:v1+v2+carry(進位)=該位置之值,每次加完判斷有無進位。 可能情況有三種 1. l1沒了l2還有,l2補完 2. l2沒了l1還有,l1補完 3. l1還有l2還有,相加。 若末端仍進位則額外宣告一點記憶體空間來存放。