- 题目描述:链接
给出两个 非空 的链表用来表示两个非负的整数。
其中,它们各自的位数是按照 逆序 的方式存储的,
并且它们的每个节点只能存储一位数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
- 解析:
题意:从左向右开始相加,注意进位问题,如果两个链表长度一样大的情况下,注意最后一次是否有进位,有的话需要新生成一个节点来存储链到新链表上
- 代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
if(l1==NULL && l2 == NULL) return NULL;
int flag = 0; //进位
int sum = 0;
struct ListNode* Node1 = l1;
struct ListNode* Node2 = l2;
struct ListNode* new_head =NULL;
struct ListNode* tmp = NULL;
struct ListNode* q = NULL;
int cnt = 0;
while((Node1 || Node2) || flag == 1)
{
sum = 0;
if(Node1){
sum += Node1->val;
Node1 = Node1->next;
}
if(Node2){
sum += Node2->val;
Node2 = Node2->next;
}
if(flag == 1){
sum += 1;
flag = 0;
}
if(sum >= 10){
sum -= 10;
flag = 1;
}
tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
tmp->val = sum;
tmp->next = NULL;
if(new_head == NULL){
new_head = tmp;
q = tmp;
}else{
q->next = tmp;
q = q->next;
}
}
return new_head;
}