問題描述:
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
以下是問題分析:
本題是將兩個數按照逆序存放在兩個鏈表里,然后求這兩個數的和,同樣以逆序的方式輸出為鏈表。此題中可能遇到的陷阱==》變量的生存周期問題(ListNode的某一變量在addTwoNumbers函數內使用,出了該范圍無效)。
以下是我按照普通套路些的代碼
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){ ListNode* res = l1,*temp; int flag = 0; int tempval; while(l1 != NULL && l2 != NULL){ tempval = l1->val + l2->val + flag; flag = tempval / 10; tempval = tempval % 10; l1->val = tempval; temp = l1; l1 = l1->next; l2 = l2->next; } if(l1 == NULL){ temp->next = l2; l1 = l2; } while(l1 != NULL){ tempval = l1->val + flag; flag = tempval / 10; tempval = tempval % 10; l1->val = tempval; temp = l1; l1 = l1->next; } if(flag){ ListNode * p = (ListNode *)malloc(sizeof(ListNode)); ListNode f(flag); p->val = f.val; p->next = f.next; temp->next = p; } return res; }歡迎小伙伴們一起探討~
新聞熱點
疑難解答