problem 2: add two numbers
Posted nosaferyao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了problem 2: add two numbers相关的知识,希望对你有一定的参考价值。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 10 void addtolist(int val, int& add, ListNode*&head, ListNode*&pre) 11 { 12 int sum = val + add; 13 if (sum >= 10){ 14 add = 1; 15 sum -= 10; 16 17 } 18 else { 19 add = 0; 20 } 21 ListNode *node = new ListNode(sum); 22 if (!head){ 23 head = node; 24 } 25 if (NULL != pre) { 26 pre->next = node; 27 } 28 pre = node; 29 } 30 31 class Solution { 32 public: 33 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 34 if (!l1 && !l2){ 35 return NULL; 36 } 37 ListNode *head = NULL; 38 ListNode *pre = NULL; 39 int add = 0; 40 while (l1 != NULL && l2 != NULL){ 41 addtolist(l1->val + l2->val, add, head, pre); 42 l1 = l1->next; 43 l2 = l2->next; 44 } 45 while (l1){ 46 addtolist(l1->val, add, head, pre); 47 l1 = l1->next; 48 } 49 while (l2){ 50 addtolist(l2->val, add, head, pre); 51 l2 = l2->next; 52 } 53 if (add){ 54 addtolist(0, add, head, pre); 55 } 56 return head; 57 } 58 };
以上是关于problem 2: add two numbers的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode - 2 - Add Two Numbers