[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:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
分析
首先保存 l1
的地址,用于程序执行完毕后返回链表。同时从首节点开始遍历两个链表,依次相加并设定一个变量保存进位值。当两个链表有一个到底后,如果 l2
还有多余的节点,则将多出的部分添加到链表 l1
的尾部,并依次进位。时间复杂度为 $$\mathcal{O}(max(m,n))$$,空间复杂度为 $$\mathcal{O}(max(m,n))$$。
/**
* 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;
}
结果
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.
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
评论已关闭