You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
将两个链表的和置于第三个链表,两个链表的两个引用同时next;
时间复杂度为O(m+n),leetcode通过时间为4ms
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ln1 = null;
int val1=0,val2=0,val3=0,in=0;
val1 = l1==null?0:l1.val;
val2 = l2==null?0:l2.val;
val3 = (val1+val2)%10;
in = (val1+val2)/10;
ln1 = new ListNode(val3);
l1 = l1.next;
l2 = l2.next;
ListNode rs = ln1;
while(l1 != null || l2 != null || in!=0)
{
val1 = l1==null?0:l1.val;
val2 = l2==null?0:l2.val;
val3 = (val1+val2+in)%10;
ln1.next = new ListNode(val3);
in = (val1+val2+in)/10;
l1 = (l1==null?null:l1.next);
l2 = (l2==null?null:l2.next);
ln1 = ln1.next;
}
return rs;
}