大佬解法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode pre = new ListNode(0);
ListNode cur = pre;
int carry = 0;
while(l1 != null || l2 != null) {
int x = l1 == null ? 0 : l1.val;
int y = l2 == null ? 0 : l2.val;
int sum = x + y + carry;
carry = sum / 10;
sum = sum % 10;
cur.next = new ListNode(sum);
cur = cur.next;
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
}
if(carry == 1) {
cur.next = new ListNode(carry);
}
return pre.next;
}
}
自己的解法
写的跟屎一样,虽然击败100%Java用户,但是写的实在是太过于复杂
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int sum=0;
ListNode ans=new ListNode();
ListNode p=ans,ptr=null;
for(;;){
if(l1!=null&&l2!=null)
{
sum=l1.val+l2.val;
if(p.val==1){
sum+=1;
}
if(sum>=10){
p.next=new ListNode(1);
p.val=sum%10;
}else{
p.val=sum;
if(l1.next!=null||l2.next!=null)//防止产生前导0
{
p.next=new ListNode();
}
}
l1=l1.next;
l2=l2.next;
ptr=l1==null?l2:l1;
p=p.next;
}
else if(ptr!=null){
int null_sum=0;
if(p.val==1){
null_sum=ptr.val+p.val;
if(null_sum>=10){
p.next=new ListNode(1);
p.val=null_sum%10;
}else{
p.val=null_sum;
if(ptr.next!=null){//防止产生前导0
p.next=new ListNode();
}
}
}
else{
p.val=ptr.val;
if(ptr.next!=null){//防止产生前导0
p.next=new ListNode();
}
}
//往后遍历
ptr=ptr.next;
p=p.next;
}else{
break;
}
}
return ans;
}
}