题解 | #链表相加(二)#
链表相加(二)
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) { // 反转链表,使个位数在前 ListNode num1 = reverse(head1); ListNode num2 = reverse(head2); // 头节点之前再创建一个节点,方便处理 ListNode hair = new ListNode(0); ListNode pointer = hair; // 进位数 int res = 0; // 从个位开始相加 while (num1 != null || num2 != null) { int sum = 0; if (num1 == null) { sum = res + num2.val; num2 = num2.next; } else if (num2 == null) { sum = res + num1.val; num1 = num1.next; } else { sum = res + num1.val + num2.val; num1 = num1.next; num2 = num2.next; } int val = sum % 10; res = sum / 10; ListNode current = new ListNode(val); pointer.next = current; pointer = pointer.next; } // 处理最后一个进位 if (res > 0) { pointer.next = new ListNode(res); } // 反转链表 return reverse(hair.next); } private ListNode reverse(ListNode head) { ListNode pre = null; ListNode current = head; while (current != null) { ListNode next = current.next; current.next = pre; pre = current; current = next; } return pre; } }