A simple code that everyone can understand. Single Pass C++ solution.


  • 0
    S
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
      		ListNode* res=new ListNode(-1);
      		ListNode* cur=res;
      		int carry=0;
            int result=0;
      		while(l1 && l2){
      			result=l1->val+carry+l2->val;
      			carry=result/10;
      			result=result%10;
      			cur->next=new ListNode(result);
      			l1=l1->next;
      			l2=l2->next;
      			cur=cur->next;
      		}
    
      		while(l1){
      			result=l1->val+carry;
      			carry=result/10;
      			result=result%10;
      			cur->next=new ListNode(result);
      			cur=cur->next;
      			l1=l1->next;
      		}
    
      		while(l2){
      			result=l2->val+carry;
      			carry=result/10;
      			result=result%10;
      			cur->next=new ListNode(result);
      			cur=cur->next;
      			l2=l2->next;
      		}
      		if(carry)
      		    cur->next=new ListNode(carry);
      		return res->next;
    
        }
    };
    

Log in to reply
 

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