使用递归算法
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { return add(l1, l2, 0); } public ListNode add(ListNode l1,ListNode l2,int carry) { if(l1==null && l2==null){ return carry == 0? null : new ListNode(carry); } if(l1==null && l2!=null){ l1 = new ListNode(0); } if(l2==null && l1!=null){ l2 = new ListNode(0); } int sum = l1.val + l2.val + carry; ListNode curr = new ListNode(sum % 10); curr.next = add(l1.next, l2.next, sum / 10); return curr; } }
偷懒相加法,超过long的范围会失败
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1==null&&l2==null){ return null; } //链表转long型 long num1 = listToLong(l1); long num2 = listToLong(l2); return longToList(num1+num2); } //链表转数据 public Long listToLong(ListNode l) { long num=0; long curr=1; int i=0; while(l!=null) { num=num+l.val*curr; curr=curr*10; l=l.next; } return num; } //数据转链表 public ListNode longToList(Long num){ ListNode l3 = new ListNode(-1); l3.next = null; ListNode c = l3; c.val=(int)(num%10); num = num/10; while(num>0){ ListNode cnext = new ListNode((int)(num%10)); cnext.next=null; c.next=cnext; num = num/10; c=c.next; } return l3; } }