4ms java solution without building new linked list


  • -1
    B
    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null)
        return l2;
        if(l2==null)
        return l1;
        ListNode p=l1;
        ListNode q=l2;
        int x=1;
        while(true)
        {
            p.val=p.val+q.val;
            ListNode t=p;
            while(t.val>9)
            {
                t.val=t.val-10;
                if(t.next==null)
                t.next=new ListNode(x);
                else
                t.next.val=t.next.val+1;
                t=t.next;
            }
         
            if(p.next==null)
            break;
            if(q.next==null)
            break;
            p=p.next;
            q=q.next;
            
        }
        if(p.next==null)
        p.next=q.next;
        return l1;
        
        
        
        
    }
    

    }


  • 3
    N

    I am wondering why we solve the problem in leetcode. As we know, prepare the interview. But sometime, I just try to save running time or save memory space by using some tricks. Just as the code above, no addition new list. But when we write for the company, is this style of code a good practice? I am afraid not. Suppose you provide me such a API, I thought I will get a new link list because you will return a list node. So when I call this function, l1 was modified and I didn't know. Maybe insidious bug occours.


Log in to reply
 

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