solution:
需要考虑进位的问题。 然后就是linked list细节了: 生成新节点等等。
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode dummy(-1); ListNode* p = &dummy; int carrier = 0; while(l1||l2){ if(l1) { carrier += l1->val; l1 = l1->next; } if(l2) { carrier += l2->val; l2 = l2->next; } p->next = new ListNode(carrier%10); p = p->next; carrier /= 10; } if(carrier){ p->next = new ListNode(carrier); p = p->next; } return dummy.next; };
No comments :
Post a Comment