代码

  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 pre = new ListNode(0);
  12. ListNode cur = pre;
  13. int carry = 0;
  14. while(l1 != null || l2 != null) {
  15. int x = l1 == null ? 0 : l1.val;
  16. int y = l2 == null ? 0 : l2.val;
  17. int sum = x + y + carry;
  18. carry = sum / 10;
  19. sum = sum % 10;
  20. cur.next = new ListNode(sum);
  21. cur = cur.next;
  22. if(l1 != null)
  23. l1 = l1.next;
  24. if(l2 != null)
  25. l2 = l2.next;
  26. }
  27. if(carry == 1) {
  28. cur.next = new ListNode(carry);
  29. }
  30. return pre.next;
  31. }
  32. }
  33. 作者:guanpengchn
  34. 链接:https://leetcode-cn.com/problems/add-two-numbers/solution/hua-jie-suan-fa-2-liang-shu-xiang-jia-by-guanpengc/
  35. 来源:力扣(LeetCode
  36. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。