lintcode 链表求和

时间:2025-05-02 16:07:31

题目要求

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

样例

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

分析

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

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/ class Solution {
public:
/*
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
ListNode * addLists(ListNode * l1, ListNode * l2) {
// write your code here
ListNode *re = new ListNode();
ListNode *r = re;
int flag = ;
while(l1 && l2){
int sum = l1->val + l2->val + flag;
flag = sum / ;
re->next = new ListNode(sum % );
re = re->next;
l1=l1->next;
l2=l2->next;
}
while(l1){
int sum = l1->val + flag;
flag = sum / ;
re->next = new ListNode(sum % );
re = re->next;
l1=l1->next;
}
while(l2){
int sum = l2->val + flag;
flag = sum / ;
re->next = new ListNode(sum % );
re = re->next;
l2=l2->next;
}
if(flag){
re->next = new ListNode(flag);
re = re->next;
}
re->next = NULL;
return r->next;
}
};