import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ public ListNode addInList (ListNode head1, ListNode head2) { // write code here // 解题思路: // 1.如果head1 为null,则返回head2,反之也是。 // 2.对head1 和 head2 进行链表反转 // 3.循环遍历 head1 不为null或head2 不为null,则取他们的值相加 // 对10取余作为新节点的值,对10取整作为下一次计算的初始值 // 向后移动链表 // 跳出循环后,需要注意初始值是否大于0 // 最后对新链表反转 if (head1 == null) { return head2; } if (head2 == null) { return head1; } ListNode r1 = reverse( head1); ListNode r2 = reverse( head2); int temp = 0; ListNode root = new ListNode(-1); ListNode cur = root; while (r1 != null || r2 != null) { int v1 = (r1 == null) ? 0 : r1.val; int v2 = (r2 == null) ? 0 : r2.val; int sum = temp + v1 + v2; temp = sum / 10; cur.next = new ListNode(sum % 10); cur = cur.next; if (r1 != null) { r1 = r1.next; } if (r2 != null) { r2 = r2.next; } } if (temp > 0) { cur.next = new ListNode(temp); } return reverse(root.next); } private ListNode reverse(ListNode head1) { if (head1 == null) { return null; } ListNode pre = null; ListNode next; while (head1 != null) { next = head1.next; head1.next = pre; pre = head1; head1 = next; } return pre; } }