您的位置:首页 > 其它

LeetCode2:Add Two Numbers

2015-06-05 20:57 375 查看
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

注意对象的引用传递过程。写得有些复杂.......

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

ListNode tai;
int carry=0;
int temp1=l1.val+l2.val;
if(temp1>=10){
temp1=temp1%10;
carry=1;
}

ListNode ans=new ListNode(temp1);
ListNode currentans=ans;
//ans.next=currentans;
while((l1=l1.next)!=null&&(l2=l2.next)!=null){
int temp=l1.val+l2.val+carry;
if(temp>=10){
temp=temp%10;
carry=1;
}else{
carry=0;
}
currentans.next=new ListNode(temp);

currentans=currentans.next;

}
if(l1==null&&l2!=null){
l2=l2.next;
}
while(l1!=null){
int temp=l1.val+carry;
if(temp>=10){
temp=temp%10;
carry=1;
}else{
carry=0;
}
currentans.next=new ListNode(temp);
currentans=currentans.next;
l1=l1.next;
}
while(l2!=null){
int temp=l2.val+carry;
if(temp>=10){
temp=temp%10;
carry=1;
}else{
carry=0;
}
currentans.next=new ListNode(temp);
currentans=currentans.next;
l2=l2.next;
}
if(carry==1){
currentans.next=new ListNode(1);
currentans=currentans.next;
}
return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: