第一次写的有些麻烦,不好,问题关键是默认两个链表长度相等,前面补0即可。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1 == null) return l2; if(l2 == null) return l1; ListNode result = new ListNode(0); ListNode res = new ListNode(0); result = res; int flag = 0; while(l1 != null || l2 != null) { int a1 = l1==null?0:l1.val; int a2 = l2==null?0:l2.val; int a = a1+a2+flag; flag = a / 10; ListNode t = new ListNode(a%10); res.next = t; res = t; l1 = l1==null?null:l1.next; l2 = l2==null?null:l2.next; } if(flag == 1) { ListNode t = new ListNode(1); res.next = t; res = t; } return result.next; } }