2 两数相加

  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 head = new ListNode(0);
  12. ListNode p = l1, q = l2, cur = head;
  13. int flag = 0;
  14. while (p != null || q != null) {
  15. int x = (p != null) ? p.val : 0;
  16. int y = (q != null) ? q.val : 0;
  17. int sum = x + y + flag;
  18. flag = sum / 10;
  19. cur.next = new ListNode(sum % 10);
  20. cur = cur.next;
  21. if (p != null) p = p.next;
  22. if (q != null) q = q.next;
  23. }
  24. if (flag > 0)
  25. cur.next = new ListNode(flag);
  26. return head.next;
  27. }
  28. }