Add
Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
记录时间,保存代码,有时间继续优化
1555 / 1555 test cases passed.
Runtime: 288
ms
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode head(0);
ListNode *p1, *p2, *p3;
p1 = l1;
p2 = l2;
p3 = &head;
int add_res = 0;
for (; p1 || p2 || add_res > 0; p1 = (p1 ? p1->next : p1), p2 = p2 ? p2->next : p2) {
p3->next = new ListNode(add_res);
p3 = p3->next;
p3->val += (p1 ? p1->val : 0) + (p2 ? p2->val : 0);
if (p3->val > 9) {
add_res = p3->val / 10;
p3->val %= 10;
} else {
add_res = 0;
}
}
p3 = head.next;
return p3;
}
本文介绍了一种算法问题的解决方案:两个非负整数以链表形式给出,数字以逆序存储,每个节点包含一个数字。通过将这两个数字相加并以链表形式返回结果。
177

被折叠的 条评论
为什么被折叠?



