lintcode 链表求和

题目要求

你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。

样例

给出两个链表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null

分析

因为是反序,所以每个位置的和直接逐一相加就可以,难点是进位,需要用到一个flag来控制进位,这里要特别记住最后还要判断一次最高位的进位。

 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 
11 class Solution {
12 public:
13     /*
14      * @param l1: the first list
15      * @param l2: the second list
16      * @return: the sum list of l1 and l2 
17      */
18     ListNode * addLists(ListNode * l1, ListNode * l2) {
19         // write your code here
20         ListNode *re  = new ListNode(0);
21         ListNode *r = re;
22         int flag = 0;
23         while(l1 && l2){
24             int sum = l1->val + l2->val + flag;
25             flag = sum / 10;
26             re->next = new ListNode(sum % 10);
27             re = re->next;
28             l1=l1->next;
29             l2=l2->next;
30         }
31         while(l1){
32             int sum = l1->val + flag;
33             flag = sum / 10;
34             re->next = new ListNode(sum % 10);
35             re = re->next;
36             l1=l1->next;
37         }
38          while(l2){
39             int sum = l2->val + flag;
40             flag = sum / 10;
41             re->next = new ListNode(sum % 10);
42             re = re->next;
43             l2=l2->next;
44         }
45         if(flag){
46             re->next = new ListNode(flag);
47             re = re->next;
48         }
49         re->next = NULL;
50         return r->next;
51     }
52 };
原文地址:https://www.cnblogs.com/liangjiahao713/p/7651109.html