You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
两个链表的值相加过程,借助carry,carry=0/1表示是否有进位,ci=(ai+bi+carry) ,进位carry=(ai+bi+carry)/10
如果a b 链表有一方到头了,则其实设为0,直到 a b全部到头,全部到头后看carry如果不等于零,则还需新增加一个点保留最高位
/** * 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) { ListNode head=new ListNode(0); ListNode result=head; ListNode p=l1; ListNode q=l2; int carry=0; while(p!=null||q!=null){ int x=(p!=null)?p.val:0; int y=(q!=null)?q.val:0; int sum=x+y+carry; int value=sum; carry=sum/10; result.next=new ListNode(value); result=result.next; if(p!=null) p=p.next; if(q!=null)q=q.next; } if(carry>0){//最后两位数求和后>10,仍需要进位 result.next=new ListNode(carry); } return head.next; } }