2 两数相加
/**n * Definition for singly-linked list.n * public class ListNode {n * int val;n * ListNode next;n * ListNo
/**n * Definition for singly-linked list.n * public class ListNode {n * int val;n * ListNode next;n * ListNode(int x) { val = x; }n * }n */nclass Solution {n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {n ListNode dummy = new ListNode(-1);n ListNode cur = dummy;n int carry = 0;n while(l1!=null || l2!=null){n int n1 = l1 == null ? 0 : l1.val;n int n2 = l2 == null ? 0 : l2.val;n int sum = n1 + n2 + carry;n carry = sum >= 10 ? 1 : 0;nn cur.next = new ListNode(sum%10);n cur = cur.next;nn if(l1 != null) l1 = l1.next;n if(l2 != null) l2 = l2.next;n }nn if(carry == 1){n cur.next = new ListNode(1);n }nn return dummy.next;n }n}
下一篇:2保