0002.两数相加
两数相加
中等难度
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
解释:342 + 465 = 807
通过次数550,058提交次数1,440,708
算法
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
struct ListNode* addTwoNumbers(struct ListNode*, struct ListNode* l2);
void print_node(struct ListNode* const);
int main(int argc, char** argv){
struct ListNode* l1 = &(struct ListNode){2, &(struct ListNode){4, &(struct ListNode){3}}};
struct ListNode* l2 = &(struct ListNode){5, &(struct ListNode){6, &(struct ListNode){4}}};
printf("l1:\n");
print_node(l1);
printf("l2:\n");
print_node(l2);
struct ListNode* output = addTwoNumbers(l1, l2);
printf("output:\n");
print_node(output);
return 0;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int add = 0;
struct ListNode* node1 = l1;
struct ListNode* node2 = l2;
struct ListNode* output = NULL;
struct ListNode* tmp0 = NULL;
struct ListNode* tmp1 = NULL;
while (node1 || node2 || add){
tmp1 = malloc(sizeof(struct ListNode));
tmp1->next = NULL;
if (node1){
add += node1->val;
node1 = node1->next;
}
if (node2){
add += node2->val;
node2 = node2->next;
}
tmp1->val = add % 10;
add = add / 10;
if (!output){
output = tmp1;
} else {
tmp0->next = tmp1;
}
tmp0 = tmp1;
}
return output;
}
void print_node(struct ListNode* const node){
if (!node){
printf("null\n");
return;
}
struct ListNode* node0 = node;
int val = node0->val;
int mul = 1;
printf("[%d", val);
while (node0->next){
node0 = node0->next;
mul *= 10;
val += node0->val * mul;
printf(", %d", node0->val);
}
printf("] %d\n", val);
}
output:
l1:
[2, 4, 3] 342
l2:
[5, 6, 4] 465
output:
[7, 0, 8] 807
时间:12ms;内存:7.4MB

浙公网安备 33010602011771号