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、根据题意可知需要把2个链表相加,但由于高位在链表头部,所以需要对链表进行反转 // 2、对每个节点相加,对10取余(%10)部分作为节点值,取整部分作为一下个节点相加的累加值 // 3、结果计算完毕后,需要对链表再次进行反转 ListNode rHead1 = resever(head1 ); ListNode rHead2 = resever(head2 ); int init = 0; ListNode root = new ListNode(-1); ListNode cur = root; while (rHead1 != null || rHead2 != null || init != 0) { int val1 = rHead1 == null ? 0 : rHead1.val ; int val2 = rHead2 == null ? 0 : rHead2.val ; int sum = init + val1 + val2; init = sum / 10; ListNode node = new ListNode(sum % 10); cur.next = node; cur = cur.next; if(rHead1 != null){ rHead1 = rHead1.next; } if(rHead2 != null){ rHead2 = rHead2.next; } } return resever(root.next); } private ListNode resever(ListNode head) { ListNode pre = null; ListNode next = null; while (head != null) { next = head.next; head.next = pre; pre = head; head = next; } return pre; } }