Linked List Math

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, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

Explanation: 342 + 465 = 807.

相似题目:
简单
- Add Binary
- Sum of Two Integers
- Add Strings
中等
- Multiply Strings
- Add Two Numbers II
- Add to Array-Form of Integer

初等数学

伪代码如下:

  • 将当前节点初始化为返回链表的哑节点 (统一节点插入操作)
  • 将进位 carry 初始化为0
  • pq 分别初始化为链表 l1l2 的头部
  • 遍历链表 l1l2 直至到达它们的尾端。
    • 将x设置为节点p的值。如果p已经到达 l1 的末尾,则将其值设置为0。
    • 将y设置为节点q的值。如过q已经到达 l2 的末尾,则将其值设置为0。
    • 设定 sum = x + y + carry
    • 更新进位的数值为,carry = sum / 10
    • 创建一个数值为(sum mod 10)的新节点,并将其设置为当前节点的下一个节点,再将当前节点指向新创建的节点
    • 同时,将p和q 前进到下一个节点
  • 检查carry是否等于1,若是,向链表尾追加一个值为1的新结点
  • 返回哑节点的下一个节点

:::info 一个循环就解决了,刚开始做的时候用了3个循环,还没有解决!!!

  • 若指向空,则赋值为0 很妙
  • curr 和 哑节点 都非常重要
  • 一个循环的话,要注意什么时候索引不能前进 :::
  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  11. ListNode dummyHead = new ListNode(0);
  12. ListNode p = l1, q = l2, curr = dummyHead;
  13. int carry = 0;
  14. while (p != null || q != null) {
  15. int x = (p == null) ? 0 : p.val;
  16. int y = (q == null) ? 0 : q.val;
  17. int sum = x + y + carry;
  18. carry = sum / 10;
  19. curr.next = new ListNode(sum % 10);
  20. curr = curr.next;
  21. if (p != null) p = p.next;
  22. if (q != null) q = q.next;
  23. }
  24. if (carry == 1) {
  25. curr.next = new ListNode(1);
  26. }
  27. return dummyHead.next;
  28. }
  29. }