题解 | #链表相加(二)#
链表相加(二)
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) { // write code here return reverse(add(reverse(head1),reverse(head2))); } public ListNode add(ListNode head1, ListNode head2){ if(head1==null){ return head2; } if(head2==null){ return head1; } ListNode tmp1 = head1; ListNode tmp2 = head2; ListNode tail = head1; int jw=0; boolean flag = true; while(head1!=null || head2!=null){ int l1 = head1!=null?head1.val:0; int l2 = head2!=null?head2.val:0; int tmp = l1+l2+jw; jw=0; if(tmp>9){ jw =1; } tmp = tmp%10; if(head1!=null){ tail = head1; flag = true; head1.val = tmp; head1 = head1.next; } if(head2!=null){ tail = head2; flag = false; head2.val = tmp; head2 = head2.next; } } if(jw>0){ tail.next = new ListNode(1); } return flag?tmp1:tmp2; } public ListNode reverse(ListNode head){ if(head==null){ return head; } ListNode l1 = head; ListNode l2 = head.next; while(l1 != null){ if(l2==null){ head.next = null; return l1; } ListNode tmp = l2.next; l2.next = l1; l1 = l2; l2 = tmp; } return l1; } }