51 ms O(n) java solution


  • 0
    F

    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    l1=revlist(l1);
    l2=revlist(l2);

        ListNode p=new ListNode(0);
        ListNode ans=p;
        while(l1!=null||l2!=null){
            if(l1!=null&&l2!=null){
            ans.next=new ListNode((l1.val+l2.val+ans.val)/10);
            ans.val=(l1.val+l2.val+ans.val)%10;
            l1=l1.next;
            l2=l2.next;
            ans=ans.next;
            }
            else if(l1!=null&&l2==null){
            ans.next=new ListNode((l1.val+ans.val)/10);
            ans.val=(l1.val+ans.val)%10;
            l1=l1.next;
            ans=ans.next;
            }
            else if(l1==null&&l2!=null){
            ans.next=new ListNode((l2.val+ans.val)/10);
            ans.val=(l2.val+ans.val)%10;
            l2=l2.next;
            ans=ans.next;
            }
        }
        return ans.val==0? revlist(p).next:revlist(p);
    
        
    }
    private ListNode revlist(ListNode n){
        if(n==null){
            return n;
        }
        ListNode tmp=null;
        while(n.next!=null){
            ListNode t=n.next;
            n.next=tmp;
            tmp=n;
            n=t;
        }
        n.next=tmp;
        return n;
    }
    

    }


Log in to reply
 

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