给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目分析
2->4->3代表342,即链表第一个节点代表个位,下一个节点代表十位,一直到尾节点,但是输出是反过来的。
个人题解
/**
* 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 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode *left = l1, *right = l2;
//进位
int carry = 0;
int iLeft = 0, iRight = 0, sum = 0;
ListNode* head = new ListNode(0);
ListNode* tmpNode = head;
while(l1 != NULL || l2 != NULL)
{
iLeft = l1 ? l1->val : 0;
iRight = l2 ? l2->val : 0;
//进位不能在new的时候进
sum = iLeft + iRight + carry;
ListNode* newNode = new ListNode(sum % 10);
carry = sum / 10;
tmpNode->next = newNode;
tmpNode = tmpNode->next;
//注意判空
if(l1)l1 = l1->next;
if(l2)l2 = l2->next;
}
if(carry)
{
ListNode* newNode = new ListNode(1);
tmpNode->next = newNode;
}
return head->next;
}
};
/*
执行用时 :12 ms, 在所有 C++ 提交中击败了99.79%的用户
内存消耗 :10.5 MB, 在所有 C++ 提交中击败了5.20%的用户
如果空间需要优化,可以在原链表上操作,但是毁坏了原链表的数据,
不一定好,需参考实际情况
*/