c++ straight forward solution


  • 0
    2

    Any suggestions to make it more concise? thx!

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            if(!l1) return l2;
            if(!l2) return l1;
            
            ListNode* newhead= new ListNode(0);
            ListNode* p=newhead;
            int carry=0,cur=0;
            
            ListNode *p1=l1,*p2=l2;
            while(p1 || p2){
              if(p1->next && !p2->next) {
                  ListNode *temp=new ListNode(0);
                  p2->next=temp;
              }  
              if(!p1->next && p2->next) {
                  ListNode *temp=new ListNode(0);
                  p1->next=temp;
              }  
              p1=p1->next;
              p2=p2->next;
            }
            
            while(l1){
                int v1=l1->val, v2=l2->val;
                cur=(v1+v2+carry)%10;
                carry=(v1+v2+carry)/10;
                
                ListNode *temp=new ListNode(cur);
                p->next=temp;
                p=p->next;
                
                l1=l1->next;
                l2=l2->next;
                
            }
            ListNode *temp=new ListNode(1);
            if (carry==1) p->next=temp;
          
            return newhead->next;
        }
    };
    

Log in to reply
 

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