JAVA O(n), easy


  • 0
    R

    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    for(ListNode lt1=l1, lt2=l2;lt1!=null||lt2!=null;lt1=lt1.next,lt2=lt2.next){
    if(lt2==null){
    for(;lt1.val>=10;){
    lt1.val=lt1.val-10;
    if(lt1.next==null){
    lt1.next = new ListNode(1);
    }
    else{
    lt1.next.val++;
    lt1=lt1.next;
    }
    }
    return l1;
    }
    if(lt1==null){
    for(;lt2.val>=10;){
    lt2.val=lt2.val-10;
    if(lt2.next==null){
    lt2.next = new ListNode(1);
    }
    else{
    lt2.next.val++;
    lt2=lt2.next;
    }
    }
    return l2;
    }
    int temp = lt1.val+lt2.val;
    if(temp>=10){
    temp=temp-10;
    if(lt1.next!=null){
    lt1.next.val++;
    }
    else if(lt2.next!=null){
    lt2.next.val++;
    }
    else {
    lt2.next = new ListNode(1);
    }

            }
            lt1.val=temp;
            lt2.val=temp;
        }
        return l1;
        
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.