题目描述

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

  1. 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
  2. 输出:7 -> 0 -> 8
  3. 原因:342 + 465 = 807

解题思路

有几点需要注意:

  • 两个链表长度不一定相等
  • 会有进位
  • 当链表长度相等时还可能会有加位,比如9999+9999就从四位数变为五位数了。

最终代码如下,时间复杂度为O(max(m,n)):

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode() : val(0), next(nullptr) {}
  7. * ListNode(int x) : val(x), next(nullptr) {}
  8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
  14. ListNode *res, *temp, *idx1, *idx2;
  15. res = new ListNode();
  16. temp = new ListNode();
  17. int curr_num, next_add=0;
  18. bool start_FLAG = true;
  19. for (idx1 = l1, idx2 = l2; idx1 || idx2;) {
  20. int idx1_val = 0, idx2_val = 0;
  21. if (idx1) {
  22. idx1_val = idx1->val;
  23. idx1 = idx1->next;
  24. }
  25. if (idx2) {
  26. idx2_val = idx2->val;
  27. idx2 = idx2->next;
  28. }
  29. curr_num = idx1_val + idx2_val + next_add;
  30. next_add = curr_num / 10;
  31. curr_num = curr_num % 10;
  32. if (start_FLAG) {
  33. res = temp;
  34. start_FLAG = false;
  35. }
  36. temp->next = new ListNode(curr_num);
  37. temp = temp->next;
  38. }
  39. if (next_add) {
  40. temp->next = new ListNode(next_add);
  41. temp = temp->next;
  42. }
  43. return res->next;
  44. }
  45. };