题解 | 链表相加(二)
链表相加(二)
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 reverseList(ListNode head1){ ListNode newList = null; ListNode cur = head1; ListNode next; while(cur!=null){ next = cur.next; cur.next = newList; newList = cur; cur = next; } return newList; } public ListNode addInList (ListNode head1, ListNode head2) { ListNode newList1= reverseList(head1); ListNode newList2 = reverseList(head2); int carry = 0; ListNode p = newList1; ListNode q = newList2; ListNode relList = null; int value1,value2,total,value; while(p!=null || q!=null ||carry!=0){ if (p!=null){ value1 = p.val; } else{ value1 = 0; } if (q!=null){ value2 = q.val; } else{ value2 = 0; } total = value1 + value2 + carry; value = total % 10; carry = total / 10; ListNode newNode = new ListNode(value); newNode.next = relList; relList = newNode; if (p!=null){ p = p.next; } if(q!=null){ q = q.next; } } return relList; } }
写的很艰辛的java版本 ,要慢慢熟悉java语法