[关闭]
@CrazyHenry 2018-01-11T19:44:58.000000Z 字数 1714 阅读 1180

Leetcode2. Add Two Numbers

ddddLeetcode刷题


wallhaven-79495.jpg-774.5kB

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero(前导零,就是不会有2->4->3->0表示342), except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

结点定义:

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(nullptr) {}//新标准使用nullptr来给指针赋初值
  7. * };
  8. */

优秀代码:

  1. //T(n)=O(max{m,n}),S(n)=O(1)
  2. /**
  3. * Definition for singly-linked list.
  4. * struct ListNode {
  5. * int val;
  6. * ListNode *next;
  7. * ListNode(int x) : val(x), next(nullptr) {}
  8. * };
  9. */
  10. class Solution
  11. {
  12. public:
  13. ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
  14. {
  15. ListNode dummy(-1); //dummy:虚拟头结点,栈区结点
  16. int carry = 0;//进位数字位,初始化为0
  17. ListNode *prev = &dummy;//工作指针指向头结点
  18. for (ListNode *pa = l1, *pb = l2;
  19. pa != nullptr || pb != nullptr;
  20. pa = pa == nullptr ? nullptr : pa->next,
  21. pb = pb == nullptr ? nullptr : pb->next,
  22. prev = prev->next)
  23. {
  24. const int ai = pa == nullptr ? 0 : pa->val;
  25. const int bi = pb == nullptr ? 0 : pb->val;
  26. const int value = (ai + bi + carry) % 10;
  27. carry = (ai + bi + carry) / 10;
  28. prev->next = new ListNode(value); //尾插法,堆区结点
  29. }
  30. if (carry > 0)
  31. prev->next = new ListNode(carry);
  32. return dummy.next;//返回第一个有效结点的指针(首结点指针)
  33. }
  34. };

image.png-173.4kB

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注