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

分析

Add Binary 很类似

代码

  1. // Add Two Numbers
  2. // 跟Add Binary 很类似
  3. // 时间复杂度O(m+n),空间复杂度O(1)
  4. class Solution {
  5. public:
  6. ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
  7. ListNode dummy(-1); // 头节点
  8. int carry = 0;
  9. ListNode *prev = &dummy;
  10. for (ListNode *pa = l1, *pb = l2;
  11. pa != nullptr || pb != nullptr;
  12. pa = pa == nullptr ? nullptr : pa->next,
  13. pb = pb == nullptr ? nullptr : pb->next,
  14. prev = prev->next) {
  15. const int ai = pa == nullptr ? 0 : pa->val;
  16. const int bi = pb == nullptr ? 0 : pb->val;
  17. const int value = (ai + bi + carry) % 10;
  18. carry = (ai + bi + carry) / 10;
  19. prev->next = new ListNode(value); // 尾插法
  20. }
  21. if (carry > 0)
  22. prev->next = new ListNode(carry);
  23. return dummy.next;
  24. }
  25. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/linear-list/linked-list/add-two-numbers.html