注意下方我圈出来的部分,一开始我采用了非常愚蠢的笨办法,就是将链表存储到动态数组中,但是一些很庞大的测试用例就过不去
通过下方我圈出来的红色部分,我们只要注意可以逐位相加,只要注意进位和循环结束的条件就可以了
这道题个人感觉非常不错,很有巧思,注释的部分是我一开始的笨方法,

java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// List<Integer> arr1=new ArrayList<Integer>();
// List<Integer> arr2=new ArrayList<Integer>();
// while(l1!=null){
// arr1.add(l1.val);
// l1=l1.next;
// }
// while(l2!=null){
// arr2.add(l2.val);
// l2=l2.next;
// }
// long sum1=0,sum2=0;
// for(int i=arr1.size()-1;i>=0;i--){
// long a= (long) Math.pow(10,i);
// sum1=sum1+arr1.get(i)*a;
// a=a/10;
// }
// for(int i=arr2.size()-1;i>=0;i--){
// long a= (long) Math.pow(10,i);
// sum2=sum2+arr2.get(i)*a;
// a=a/10;
// }
// long sum=sum1+sum2;
// // 特殊情况:如果和为0,直接返回一个节点值为0的链表
// if (sum == 0) {
// return new ListNode(0);
// }
// ListNode newarr = new ListNode(); // 创建链表的头节点
// ListNode current = newarr; // 当前节点,初始指向头节点
// while (sum > 0) {
// int b = (int) (sum % 10); // 取出个位数字
// sum = sum / 10; // 去掉个位数字
// current.next = new ListNode(b); // 创建新节点
// current = current.next; // 移动到下一个节点
// }
// return newarr.next; // 返回结果链表的有效部分,去掉虚拟头节点
ListNode head=new ListNode(-1); //虚拟头结点,医院从current.next开始挂新结点,答案也从head.next开始
ListNode current=head;
int jinwei=0; //记录是否进位,如果
while(l1!=null || l2!=null || jinwei!=0){
int sum=jinwei; //当前列的值要加上进位,所以如果是1+9,循环条件还有一个jinwei不为0
if(l1!=null){
sum=sum+l1.val;
l1=l1.next;
}
if(l2!=null){
sum=sum+l2.val;
l2=l2.next;
}
jinwei=sum/10; //计算是否有进位
current.next=new ListNode(sum%10); //创建新结点,并且赋值
current=current.next;
}
return head.next; //去掉虚拟头结点
}
}