【题解】【链表】【Leetcode】Add Two Numbers

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

思路:乍一看以为是大整数,实则相当简单,比Add Binary还要简单

代码:

 1 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
 2     return addTwoDigit(l1,l2,0);
 3 }
 4 ListNode *addTwoDigit(ListNode *d1, ListNode *d2, int carry){
 5     int sum = carry;
 6     ListNode *n1 = d1, *n2 = d2;//不要轻易修改输入参数, 尤其是链表问题中
 7     if(d1 != NULL){
 8         sum += d1->val;
 9         n1 = d1->next;
10     }
11     if(d2 != NULL){
12         sum += d2->val;
13         n2 = d2->next;
14     }
15     ListNode *newNode = new ListNode(sum%10);
16     
17     if(d1 == NULL && d2 == NULL){
18         if(sum == 0)
19             return NULL;//Avoid test case:{0}, {0} => {0,0}
20         return newNode;
21     }
22     
23     ListNode *nextNode = addTwoDigit(n1, n2, sum/10);
24     newNode->next = nextNode;
25     return newNode;
26 }

 

posted on 2014-02-02 15:56  小唯THU  阅读(225)  评论(0编辑  收藏  举报

导航