Add two numbers represented by linked lists | Practice | GeeksforGeeks

Given two numbers represented by two linked lists of size N and M. The task is to return a sum list. 
The sum list is a linked list representation of the addition of two input numbers from the last.
Example 1:
Input:
N = 2
valueN[] = {4,5}
M = 3
valueM[] = {3,4,5}
Output: 3 9 0  
Explanation: For the given two linked
list (4 5) and (3 4 5), after adding
the two linked list resultant linked
list will be (3 9 0).
Example 2:
Input:
N = 2
valueN[] = {6,3}
M = 1
valueM[] = {7}
Output: 7 0
Explanation: For the given two linked
list (6 3) and (7), after adding the
two linked list resultant linked list
will be (7 0).
Your Task:
The task is to complete the function addTwoLists() which has node reference of both the linked lists and returns the head of the sum list.   
Expected Time Complexity: O(N+M)
Expected Auxiliary Space: O(Max(N,M)) for the resultant list.
Constraints:
1 <= N, M <= 5000
+1
shahabuddinbravo40in 11 hours
class Solution{   public:   //Function to add two numbers represented by linked list.   struct Node* addTwoLists(struct Node* first, struct Node* second)   {       Node *first_reverse=reverse(first);       Node *second_reverse=reverse(second);              Node *list=new Node(-1),*sum=list;       int carry=0,r,temp;       while(first_reverse && second_reverse)       {            temp=(first_reverse->data+second_reverse->data)+carry;                   r=temp%10;                      list->next=new Node(r);           list=list->next;                      first_reverse=first_reverse->next;           second_reverse=second_reverse->next;                       carry=temp/10;       }              if(first_reverse==NULL){           while(second_reverse)           {               temp=(second_reverse->data)+carry;                              r=temp%10;                              list->next=new Node(r);               list=list->next;                              second_reverse=second_reverse->next;                              carry=temp/10;           }       }              if(second_reverse==NULL){           while(first_reverse)           {               temp=(first_reverse->data)+carry;               r=temp%10;                              list->next=new Node(r);               list=list->next;                              first_reverse=first_reverse->next;                              carry=temp/10;           }       }              if(first_reverse==NULL && second_reverse==NULL && carry!=0){           list->next=new Node(carry);           list=list->next;       }              sum=sum->next;              return reverse(sum);   }      Node* reverse(Node *head){       Node *prev=NULL,*ptr=head,*ptr1=head;              while(ptr1)       {          ptr1=ptr1->next;          ptr->next=prev;          prev=ptr;          ptr=ptr1;       }       return prev;   }   };
0
avikumarking9 hours ago
Use pen and paper to understand this better.
yeah, kind of a lengthy but easy solution.
class Solution
{
    public:
   Node*rev(Node*head,int &len)
    {
        if(!head)
        return head;
        Node*trail=NULL;
        while(head)
        {
            len++;
            Node*temp=head;
            head=head->next;
            temp->next=trail;
            trail=temp;
        }
        return trail;
    }
    struct Node* addTwoLists(struct Node* first, struct Node* second)
    {
        if(!first)
        return second;
        if(!second)
        return first;
        int lenF=0;
        int lenS=0;
        first=rev(first,lenF);
        second=rev(second,lenS);
        if(lenF>=lenS)
        {
            int c=0;
            Node*head=first;
            while(second)
            {
                int ele=first->data+second->data+c;
                c=ele/10;
                ele=ele%10;
                first->data=ele;
                first=first->next;
                second=second->next;
            }
            if(c==0)
            return rev(head,lenF);
            while(first && c!=0)
            {
                int ele=first->data+c;
                c=ele/10;
                ele=ele%10;
                first->data=ele;
                first=first->next;
            }
            if(c!=0)
            {
                first=head;
                Node*trail=NULL;
                while(first)
                {
                    trail=first;
                    first=first->next;
                }
                trail->next=new Node(c);
            }
            return rev(head,lenF);
        }
        else
        {
            int c=0;
            Node*head=second;
            while(first)
            {
                int ele=first->data+second->data+c;
                c=ele/10;
                ele=ele%10;
                second->data=ele;
                first=first->next;
                second=second->next;
            }
            if(c==0)
            return rev(head,lenS);
            while(second && c!=0)
            {
                int ele=second->data+c;
                c=ele/10;
                ele=ele%10;
                second->data=ele;
                second=second->next;
            }
            if(c!=0)
            {
                second=head;
                Node*trail=NULL;
                while(second)
                {
                    trail=second;
                    second=second->next;
                }
                trail->next=new Node(c);
            }
            return rev(head,lenF);
        }
        return NULL;
    }
};
0
mannukhurana1039721 hours ago
java 
180/200 test cases pass
 
static Node addTwoLists(Node first, Node second){
        
        if(first==null || second==null){
            return first == null?second:first;
        }
        
        String FNum="";
        String SNum="";
        
        
        while(first!=null){
            FNum+=first.data;
            first = first.next;
        }
        while(second!=null){
            SNum+=second.data;
            second = second.next;
        }
       
        java.math.BigInteger n1 = new java.math.BigInteger(FNum);
        java.math.BigInteger n2 = new java.math.BigInteger(SNum);
        String finalStr = n1.add(n2).toString();
        
        first = new Node(0);
        Node temp = first;
        for(int i=0; i<finalStr.length(); i++){
            temp.next = new Node(Integer.parseInt(String.valueOf(finalStr.charAt(i))));
            temp = temp.next;
        }
        
        
        return first.next;
        
    }
 
+1
bipulharsh1231 day ago
struct Node* addTwoLists(struct Node* first, struct Node* second)   {       // code here       int sum=0;       first = reverse(first);       second = reverse(second);       Node *result=nullptr, *new_n=nullptr;       while(first || second || sum){           sum += (first?first->data:0)+(second?second->data:0);           if(first)               first = first->next;           if(second)               second = second->next;           new_n = new Node(sum%10);           new_n->next = result;           result = new_n;           sum /= 10; // Leaving carry value       }       return result;   }
0
hk63017359395 days ago
JAVA SOLUTION.......................
class Solution{   //Function to add two numbers represented by linked list.   static Node addTwoLists(Node first, Node second){       String s="",s1="";       Node dummy = new Node(0);       Node l=dummy;       Node temp=first;       while(temp!=null){           s+=temp.data;           temp=temp.next;       }       temp=second;       while(temp!=null){           s1+=temp.data;           temp=temp.next;       }      java.math.BigInteger n1= new java.math.BigInteger(s);       java.math.BigInteger n2= new java.math.BigInteger(s1);       java.math.BigInteger n=n1.add(n2);       String h=n.toString();       //System.out.println(h);       for(int i=0;i<h.length();i++){           l.next=new Node(Integer.parseInt(String.valueOf(h.charAt(i))));       l=l.next;       }       return dummy.next;   }}
0
dev1711 week ago
simple C++ reverse and take carry forward 
 Node *reverse(struct Node* k){
        Node *prev=NULL;
        while(k){
            Node* next=k->next;
            k->next=prev;
            prev=k;
            k=next;
        }
        return prev;
    }
    struct Node* addTwoLists(struct Node* first, struct Node* second)
    {
        // code here
        Node * k=reverse(first);
        Node *j=reverse(second);
        
        int carry=0;
        Node *dummy=new Node(-1),*last=dummy;
        while(k && j){
            int val=k->data+j->data+carry;
            Node *temp=new Node(val%10);
            last->next=temp;
            last=temp;
            carry=val/10;
            k=k->next;
            j=j->next;
        }
        while(k){
              int val=k->data+carry;
            Node *temp=new Node(val%10);
            last->next=temp;
            last=temp;
            carry=val/10;
            k=k->next;

        }
         while(j){
              int val=j->data+carry;
            Node *temp=new Node(val%10);
            last->next=temp;
            last=temp;
            carry=val/10;
            j=j->next;

        }
        if(carry>0){
            last->next=new Node(carry);
        }
        return reverse(dummy->next);
        
    }
0
someshthakur901 week ago
why my code does not work for large test cases!!
 static Node addTwoLists(Node first, Node second){          if(first==null&&second==null) {           return null;       }       if(first==null&&second!=null){           return second;       }       if(first!=null&&second==null){           return first;       }       long num1=0,num=0,sum=0;             while(first!=null){           num1 = num1*10 + first.data;           first = first.next;       }       while(second!=null){           num = num*10 + second.data;           second = second.next;       }      //System.out.println(num);      // System.out.println(num1);       sum = num1 + num;      //System.out.println(sum);      long d = sum%10;       Node sumList = new Node((int)d);       sum=sum/10;       Node temp = sumList;       temp.next=null;       while(temp!=null&&sum!=0){                      long D = sum%10;           temp.next = new Node((int)D);                       temp = temp.next;           sum = sum/10;       }             Node current=sumList,prev=null,next=null;       while(current!=null){           next = current.next;           current.next=prev;           prev = current;           current = next;       }       sumList = prev;       return sumList;
 
0
satyamagarwal2491 week ago
import sys
sys.setrecursionlimit(10**7)
class Solution:
    def addTwoLists(self, first, second):
        self.result = None
        l1 = l2 = 0
        
        node = first
        while node:
            node = node.next
            l1 += 1
        
        node = second
        while node:
            node = node.next
            l2 += 1
         
        if l2 > l1:
            first, second = second, first
            l1, l2 = l2, l1

        k = l1 - l2
        f = first
        s = second
        while k > 0:
            f = f.next
            k -= 1
            
        self.carry = self.addUtil(f,s)
        # print('self.carry', self.carry)
        carry = self.addRest(first, l1 - l2)
        if carry:
            self.insertBegin(carry)
        return self.result

    def addRest(self, f, k):
        if k == 0:
            return self.carry
        carry = self.addRest(f.next, k-1)
        sum_ = f.data + carry
        # print('sum_', sum_)
        self.insertBegin(sum_%10)
        return sum_ // 10
            
        
    def addUtil(self, a, b):
        if a is None:
            return 0
        carry = self.addUtil(a.next, b.next)
        sum_ = a.data + b.data + carry
        self.insertBegin(sum_%10)
        return sum_ // 10
    
    def insertBegin(self, data):
        temp = Node(data)
        temp.next = self.result
        self.result = temp

+1
chinmayanaokar2 weeks ago
public Node addTwoLists(Node first, Node second)       {          if(first ==null || second==null)          {              return first==null ?  second : first;          }          int carry=0;          Node third=new Node(0);          while(first !=null || second !=null ||  carry !=0)          {              int val_1= ( first  ==null ?  0 : first.data);              int val_2= ( second ==null ?  0 : second.data);              int sum= val_1 + val_2 + carry;              int newVal= sum%10;              Node p= new Node(newVal);              third.next=p;              third=p;                            carry= sum/10;              first= ( first==null ? null : first.next );              second= ( second ==null ? null  : second.next );          }          return third.next;
+3
souravdas62 weeks ago
class Solution{   public:   Node*reverse(Node*head){       Node*prev=NULL,*nex=NULL,*curr=head;       while(curr!=NULL){           nex=curr->next;           curr->next=prev;           prev=curr;           curr=nex;       }       return prev;   }   //Function to add two numbers represented by linked list.   struct Node* addTwoLists(struct Node* first, struct Node* second)   {       first=reverse(first);       second=reverse(second);       Node*curr=NULL,*res=NULL,*t;       int s=0;       int c=0;       while(first!=NULL or second!=NULL){           s=c+(first?first->data:0)+(second?second->data:0);           c=(s>=10)?1:0;           s=s%10;           t=new Node(s);           if(res==NULL)res=t;           else curr->next=t;           curr=t;           if(first)first=first->next;           if(second)second=second->next;       }       if(c>0){           t=new Node(c);           curr->next=t;       }       res=reverse(res);       return res;   }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.