/*
    Definition for singly-linked list.
    public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
    }
    /
    class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode pre = new ListNode(0);
    ListNode cur = pre;
    int carry = 0;
    while(l1 != null || l2 != null) {
    int x = l1 == null ? 0 : l1.val;
    int y = l2 == null ? 0 : l2.val;
    int sum = x + y + carry;

    carry = sum / 10;
    sum = sum % 10;
    cur.next = new ListNode(sum);

    1. cur = cur.next;<br /> if(l1 != null)<br /> l1 = l1.next;<br /> if(l2 != null)<br /> l2 = l2.next;<br /> }<br /> if(carry == 1) {<br /> cur.next = new ListNode(carry);<br /> }<br /> return pre.next;<br /> }<br />}

    作者:guanpengchn
    链接:https://leetcode-cn.com/problems/add-two-numbers/solution/hua-jie-suan-fa-2-liang-shu-xiang-jia-by-guanpengc/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    /**

    • Definition for singly-linked list.
    • public class ListNode {
    • int val;
    • ListNode next;
    • ListNode() {}
    • ListNode(int val) { this.val = val; }
    • ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    • } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

      1. ListNode pre = new ListNode();
      2. ListNode cru = pre;
      3. //进位
      4. int corry = 0;
      5. while(l1 != null || l2 !=null ){
      6. int x = l1 == null? 0:l1.val;
      7. int y = l2 == null? 0:l2.val;
      8. //注意要加进位
      9. int sum = x + y + corry;
      10. corry = sum/10;
      11. sum = sum%10;
      12. cru.next = new ListNode(sum);
      13. cru = cru.next;
      14. //为空就不能继续下跳
      15. if(l1!=null){
      16. l1 = l1.next;
      17. }
      18. if(l2!=null){
      19. l2 = l2.next;
      20. }
      21. }
      22. //如果最后一步还有进位,当然进位最大为1
      23. if(corry == 1){
      24. cru.next = new ListNode(corry);
      25. }
      26. //注意pre是头节点,而返回要从下一个开始
      27. return pre.next;

      } }

    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 root = new ListNode(0);
    12. ListNode cursor = root;
    13. int carry = 0;
    14. while(l1 != null || l2 != null || carry != 0) {
    15. int l1Val = l1 != null ? l1.val : 0;
    16. int l2Val = l2 != null ? l2.val : 0;
    17. int sumVal = l1Val + l2Val + carry;
    18. carry = sumVal / 10;
    19. ListNode sumNode = new ListNode(sumVal % 10);
    20. cursor.next = sumNode;
    21. cursor = sumNode;
    22. if(l1 != null) l1 = l1.next;
    23. if(l2 != null) l2 = l2.next;
    24. }
    25. return root.next;
    26. }
    27. }

    image.png