题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
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) { if (head1 == null) { return head2; } if (head2 == null) { return head1; } ListNode head1R = reverse(head1); ListNode head2R = reverse(head2); ListNode newHead = new ListNode(-1); ListNode curNode = newHead; int jinwei = 0; while (head1R != null || head2R != null) { int val = jinwei; if (head1R != null) { val += head1R.val; head1R = head1R.next; } if (head2R != null) { val += head2R.val; head2R = head2R.next; } jinwei = val / 10; curNode.next = new ListNode(val % 10); curNode = curNode.next; } if (jinwei > 0) { curNode.next = new ListNode(jinwei); } return reverse(newHead.next); } public ListNode reverse(ListNode head) { if (head == null || head.next == null) { return head; } ListNode curNode = head; ListNode preNode = null; while (curNode != null) { ListNode nextNode = curNode.next; curNode.next = preNode; preNode = curNode; curNode = nextNode; } return preNode; } }