神楽坂雪紀的投研笔记

呐、现在可以和你见面吗?我、等着你哟......

0%

【LeetCode】【0002】Add Two Numbers

描述

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

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

1
2
3
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

分析

首先保存 l1 的地址,用于程序执行完毕后返回链表。同时从首节点开始遍历两个链表,依次相加并设定一个变量保存进位值。当两个链表有一个到底后,如果 l2 还有多余的节点,则将多出的部分添加到链表 l1 的尾部,并依次进位。时间复杂度为 ,空间复杂度为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *l = l1;
int sum = 0, div = 0;
sum = l1->val + l2->val;
div = sum / 10;
l1->val = sum % 10;
while (l1->next && l2->next) {
l1 = l1->next;
l2 = l2->next;
sum = l1->val + l2->val + div;
div = sum / 10;
l1->val = sum % 10;
}
if (l2->next)
l1->next = l2->next;

while(l1->next && div) {
l1 = l1->next;
sum = l1->val + div;
div = sum / 10;
l1->val = sum % 10;
}
if (!div)
return l;
l1->next = malloc(sizeof(struct ListNode));
l1 = l1->next;
l1-> val = 1;
l1->next = NULL;
return l;
}

结果

1
2
Runtime: 28 ms, faster than 69.70% of C online submissions for Add Two Numbers.
Memory Usage: 17.3 MB, less than 81.08% of C online submissions for Add Two Numbers.