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
注意对象的引用传递过程。写得有些复杂.......
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { 11 12 ListNode tai; 13 int carry=0; 14 int temp1=l1.val+l2.val; 15 if(temp1>=10){ 16 temp1=temp1%10; 17 carry=1; 18 } 19 20 ListNode ans=new ListNode(temp1); 21 ListNode currentans=ans; 22 //ans.next=currentans; 23 while((l1=l1.next)!=null&&(l2=l2.next)!=null){ 24 int temp=l1.val+l2.val+carry; 25 if(temp>=10){ 26 temp=temp%10; 27 carry=1; 28 }else{ 29 carry=0; 30 } 31 currentans.next=new ListNode(temp); 32 33 currentans=currentans.next; 34 35 36 } 37 if(l1==null&&l2!=null){ 38 l2=l2.next; 39 } 40 while(l1!=null){ 41 int temp=l1.val+carry; 42 if(temp>=10){ 43 temp=temp%10; 44 carry=1; 45 }else{ 46 carry=0; 47 } 48 currentans.next=new ListNode(temp); 49 currentans=currentans.next; 50 l1=l1.next; 51 } 52 while(l2!=null){ 53 int temp=l2.val+carry; 54 if(temp>=10){ 55 temp=temp%10; 56 carry=1; 57 }else{ 58 carry=0; 59 } 60 currentans.next=new ListNode(temp); 61 currentans=currentans.next; 62 l2=l2.next; 63 } 64 if(carry==1){ 65 currentans.next=new ListNode(1); 66 currentans=currentans.next; 67 } 68 return ans; 69 } 70 }
原文:http://www.cnblogs.com/gonewithgt/p/4555570.html