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.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
思路:链表合并与实现加法运算的结合版。有三种情况:
1.两个链表都不为空同时判断是否有进位,设置标志位,取余,处除10
2.一个链表为空另一个不为空同时判断是否有进位,若有进位与1判断相同,若无进位直接将链接追加到新链表尾部。
3.两个链表都为空同时判断是否有进位,有进位在尾部追加1。
1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 2 ListNode head = null; 3 ListNode rear = null; 4 int flag = 0; 5 ListNode node = null; 6 while(l1!=null&&l2!=null) {//处理两个链表对应位置都不为0的情况 7 if(flag==1) {//是否进位 8 node = new ListNode((l1.val+l2.val+1)%10); 9 }else { 10 node = new ListNode((l1.val+l2.val)%10); 11 }//进位 12 flag = (l1.val+l2.val+flag)/10; 13 if(head==null) {//头节点为空 14 head = node; 15 rear = head; 16 }else { 17 rear.next = node; 18 rear = rear.next; 19 } 20 l1 = l1.next; 21 l2 = l2.next; 22 } 23 //有进位需要进行特殊处理。比如5+5=10,1+99=100。 24 while(flag==1) {//有一个链表对应位置为空,同时有进位 25 if(l1==null&&l2==null) { 26 node = new ListNode(1); 27 flag = 0; 28 } 29 else { 30 if(l1!=null) { 31 node = new ListNode((l1.val+1)%10); 32 flag = (l1.val+1)/10; 33 l1 = l1.next; 34 } 35 if(l2!=null) { 36 node = new ListNode((l2.val+1)%10); 37 flag = (l2.val+1)/10; 38 l2 = l2.next; 39 } 40 } 41 rear.next = node; 42 rear = rear.next; 43 } 44 //无进位,只需要把l1或l2剩下的节点追加到新链表中 45 while(l1!=null) { 46 rear.next = l1; 47 rear = rear.next; 48 l1 = l1.next; 49 } 50 while(l2!=null) { 51 rear.next = l2; 52 rear = rear.next; 53 l2 = l2.next; 54 } 55 return head; 56 57 }