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
思路:用carry储存进位,不要漏掉最后一位,判断carry是0还是1
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
if (!l1) {
return l2;
} else if (!l2) {
return l1;
}
ListNode dummy(-1);
int carry = 0;
ListNode *prev = &dummy;
for (auto p = l1, q = l2; p != NULL || q != NULL; p = p?p->next:NULL, q = q?q->next:NULL, prev = prev->next) {
const int a = p?p->val:0;
const int b = q?q->val:0;
int value = (a+b+carry)%10;
carry = (a+b+carry)/10;
prev->next = new ListNode(value);
}
if (carry == 1) {
prev->next = new ListNode(carry);
}
return dummy.next;
}
};
本文介绍了一种使用链表实现两个非负整数相加的方法。输入的两个链表以逆序方式存储数字,并且每个节点包含一个数字。文章提供了一个C++实现示例,展示了如何遍历两个链表,逐位相加并处理进位。
746

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



