1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
* 求两个 List 相加产生的新的一个 List。
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) * Output: 7 -> 0 -> 8 //注意有进位 */
* Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */
public ListNode (ListNode l1, ListNode l2) { int carry = 0; ListNode dummy = new ListNode(0); ListNode cur = dummy; while (l1 != null || l2 != null) { int a = 0; int b = 0; if (l1 != null) { a = l1.val; l1 = l1.next; } if (l2 != null) { b = l2.val; l2 = l2.next; } cur.next = new ListNode((a + b + carry) % 10); carry = (a + b + carry) / 10; cur = cur.next; } if (carry != 0) cur.next = new ListNode(carry); return dummy.next; }
|
近期评论