力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台 public ListNode addInList (ListNode head1, ListNode head2) { // write code here // 进行判空处理 if (head1 == null) return head2; if (head2 == null) { return head1; } //先进行链表反转,再相加 ListNode h1 = reverse(head1); ListNode h2 = reverse(head2); //存放结果集 ListNode head = new ListNode(-1); ListNode res = head; int temp = 0; while (h1 != null || h2 != null || temp > 0) { if (h1 != null) { temp = temp + h1.val; h1 = h1.next; } if (h2 != null) { temp = temp + h2.val; h2 = h2.next; } res.next = new ListNode(temp % 10); res = res.next; temp = temp / 10; } return reverse( head.next); } public ListNode reverse(ListNode node) { if (node == null) return node; ListNode pre = null, next = null; while (node != null) { next = node.next; node.next = pre; pre = node; node = next; } return pre; }