Add two numbers represented by linked lists | Set 2

Given two numbers represented by two linked lists, write a function that returns the sum of the two linked lists in the form of a list.
Note: It is not allowed to modify the lists. Also, not allowed to use explicit extra space (Hint: Use Recursion).
Example :
Input: First List: 5->6->3, Second List: 8->4->2Â
Output: Resultant list: 1->4->0->5
Explanation: Sum of 563 and 842 is 1405
We have discussed a solution here which is for linked lists where the least significant digit is the first node of lists and the most significant digit is the last node. In this problem, the most significant digit is the first node and the least significant digit is the last node and we are not allowed to modify the lists. Recursion is used here to calculate the sum from right to left.
Following are the steps.Â
1) Calculate sizes of given two linked lists.Â
2) If sizes are same, then calculate sum using recursion. Hold all nodes in recursion call stack till the rightmost node, calculate the sum of rightmost nodes and forward carry to the left side.Â
3) If size is not same, then follow below steps:Â
….a) Calculate difference of sizes of two linked lists. Let the difference be diffÂ
….b) Move diff nodes ahead in the bigger linked list. Now use step 2 to calculate the sum of the smaller list and right sub-list (of the same size) of a larger list. Also, store the carry of this sum.Â
….c) Calculate the sum of the carry (calculated in the previous step) with the remaining left sub-list of a larger list. Nodes of this sum are added at the beginning of the sum list obtained the previous step.
Below is a dry run of the above approach:
Below is the implementation of the above approach.Â
C++
// A C++ recursive program to add two linked lists#include <bits/stdc++.h>using namespace std;Â
// A linked List Nodeclass Node {public:Â Â Â Â int data;Â Â Â Â Node* next;};Â
typedef Node node;Â
/* A utility function to inserta node at the beginning of linked list */void push(Node** head_ref, int new_data){Â Â Â Â /* allocate node */Â Â Â Â Node* new_node = new Node[(sizeof(Node))];Â
    /* put in the data */    new_node->data = new_data;Â
    /* link the old list of the new node */    new_node->next = (*head_ref);Â
    /* move the head to point to the new node */    (*head_ref) = new_node;}Â
/* A utility function to print linked list */void printList(Node* node){Â Â Â Â while (node != NULL) {Â Â Â Â Â Â Â Â cout << node->data << " ";Â Â Â Â Â Â Â Â node = node->next;Â Â Â Â }Â Â Â Â cout << endl;}Â
// A utility function to swap two pointersvoid swapPointer(Node** a, Node** b){Â Â Â Â node* t = *a;Â Â Â Â *a = *b;Â Â Â Â *b = t;}Â
/* A utility function to get size of linked list */int getSize(Node* node){Â Â Â Â int size = 0;Â Â Â Â while (node != NULL) {Â Â Â Â Â Â Â Â node = node->next;Â Â Â Â Â Â Â Â size++;Â Â Â Â }Â Â Â Â return size;}Â
// Adds two linked lists of same size// represented by head1 and head2 and returns// head of the resultant linked list. Carry// is propagated while returning from the recursionnode* addSameSize(Node* head1, Node* head2, int* carry){    // Since the function assumes linked lists are of same    // size, check any of the two head pointers    if (head1 == NULL)        return NULL;Â
    int sum;Â
    // Allocate memory for sum node of current two nodes    Node* result = new Node[(sizeof(Node))];Â
    // Recursively add remaining nodes and get the carry    result->next        = addSameSize(head1->next, head2->next, carry);Â
    // add digits of current nodes and propagated carry    sum = head1->data + head2->data + *carry;    *carry = sum / 10;    sum = sum % 10;Â
    // Assign the sum to current node of resultant list    result->data = sum;Â
    return result;}Â
// This function is called after the// smaller list is added to the bigger// lists's sublist of same size. Once the// right sublist is added, the carry// must be added toe left side of larger// list to get the final result.void addCarryToRemaining(Node* head1, Node* cur, int* carry,                         Node** result){    int sum;Â
    // If diff. number of nodes are not traversed, add carry    if (head1 != cur) {        addCarryToRemaining(head1->next, cur, carry,                            result);Â
        sum = head1->data + *carry;        *carry = sum / 10;        sum %= 10;Â
        // add this node to the front of the result        push(result, sum);    }}Â
// The main function that adds two linked lists// represented by head1 and head2. The sum of// two lists is stored in a list referred by resultvoid addList(Node* head1, Node* head2, Node** result){Â Â Â Â Node* cur;Â
    // first list is empty    if (head1 == NULL) {        *result = head2;        return;    }Â
    // second list is empty    else if (head2 == NULL) {        *result = head1;        return;    }Â
    int size1 = getSize(head1);    int size2 = getSize(head2);Â
    int carry = 0;Â
    // Add same size lists    if (size1 == size2)        *result = addSameSize(head1, head2, &carry);Â
    else {        int diff = abs(size1 - size2);Â
        // First list should always be larger than second        // list. If not, swap pointers        if (size1 < size2)            swapPointer(&head1, &head2);Â
        // move diff. number of nodes in first list        for (cur = head1; diff--; cur = cur->next)            ;Â
        // get addition of same size lists        *result = addSameSize(cur, head2, &carry);Â
        // get addition of remaining first list and carry        addCarryToRemaining(head1, cur, &carry, result);    }Â
    // if some carry is still there, add a new node to the    // front of the result list. e.g. 999 and 87    if (carry)        push(result, carry);}Â
// Driver codeint main(){Â Â Â Â Node *head1 = NULL, *head2 = NULL, *result = NULL;Â
    int arr1[] = { 9, 9, 9 };    int arr2[] = { 1, 8 };Â
    int size1 = sizeof(arr1) / sizeof(arr1[0]);    int size2 = sizeof(arr2) / sizeof(arr2[0]);Â
    // Create first list as 9->9->9    int i;    for (i = size1 - 1; i >= 0; --i)        push(&head1, arr1[i]);Â
    // Create second list as 1->8    for (i = size2 - 1; i >= 0; --i)        push(&head2, arr2[i]);Â
    addList(head1, head2, &result);Â
    printList(result);Â
    return 0;}Â
// This code is contributed by rathbhupendra |
C
// A C recursive program to add two linked listsÂ
#include <stdio.h>#include <stdlib.h>Â
// A linked List Nodestruct Node {Â Â Â Â int data;Â Â Â Â struct Node* next;};Â
typedef struct Node node;Â
/* A utility function to insert a   node at the beginning of * linked list */void push(struct Node** head_ref, int new_data){    /* allocate node */    struct Node* new_node        = (struct Node*)malloc(sizeof(struct Node));Â
    /* put in the data */    new_node->data = new_data;Â
    /* link the old list of the new node */    new_node->next = (*head_ref);Â
    /* move the head to point to the new node */    (*head_ref) = new_node;}Â
/* A utility function to print linked list */void printList(struct Node* node){    while (node != NULL) {        printf("%d ", node->data);        node = node->next;    }    printf("n");}Â
// A utility function to swap two pointersvoid swapPointer(Node** a, Node** b){Â Â Â Â node* t = *a;Â Â Â Â *a = *b;Â Â Â Â *b = t;}Â
/* A utility function to get size    of linked list */int getSize(struct Node* node){    int size = 0;    while (node != NULL) {        node = node->next;        size++;    }    return size;}Â
// Adds two linked lists of same // size represented by head1// and head2 and returns head of // the resultant linked list.// Carry is propagated while // returning from the recursionnode* addSameSize(Node* head1,                  Node* head2, int* carry){    // Since the function assumes    // linked lists are of same    // size, check any of the two     // head pointers    if (head1 == NULL)        return NULL;Â
    int sum;Â
    // Allocate memory for sum     // node of current two nodes    Node* result = (Node*)malloc(sizeof(Node));Â
    // Recursively add remaining nodes    // and get the carry    result->next        = addSameSize(head1->next,                       head2->next, carry);Â
    // add digits of current nodes     // and propagated carry    sum = head1->data + head2->data + *carry;    *carry = sum / 10;    sum = sum % 10;Â
    // Assigne the sum to current     // node of resultant list    result->data = sum;Â
    return result;}Â
// This function is called after // the smaller list is added// to the bigger lists's sublist // of same size. Once the// right sublist is added, the // carry must be added toe left// side of larger list to get // the final result.void addCarryToRemaining(Node* head1,                          Node* cur, int* carry,                         Node** result){    int sum;Â
    // If diff. number of nodes are     // not traversed, add carry    if (head1 != cur) {        addCarryToRemaining(head1->next,                            cur, carry,                            result);Â
        sum = head1->data + *carry;        *carry = sum / 10;        sum %= 10;Â
        // add this node to the front of the result        push(result, sum);    }}Â
// The main function that adds two // linked lists represented// by head1 and head2. The sum of// two lists is stored in a// list referred by resultvoid addList(Node* head1, Â Â Â Â Â Â Â Â Â Â Â Â Â Node* head2, Node** result){Â Â Â Â Node* cur;Â
    // first list is empty    if (head1 == NULL) {        *result = head2;        return;    }Â
    // second list is empty    else if (head2 == NULL)    {        *result = head1;        return;    }Â
    int size1 = getSize(head1);    int size2 = getSize(head2);Â
    int carry = 0;Â
    // Add same size lists    if (size1 == size2)        *result = addSameSize(head1, head2, &carry);Â
    else {        int diff = abs(size1 - size2);Â
        // First list should always be         // larger than second        // list. If not, swap pointers        if (size1 < size2)            swapPointer(&head1, &head2);Â
        // move diff. number of nodes in first list        for (cur = head1; diff--; cur = cur->next)            ;Â
        // get addition of same size lists        *result = addSameSize(cur,                               head2, &carry);Â
        // get addition of remaining first list and carry        addCarryToRemaining(head1,                             cur, &carry, result);    }Â
    // if some carry is still there, add a new node to the    // front of the result list. e.g. 999 and 87    if (carry)        push(result, carry);}Â
// Driver codeint main(){Â Â Â Â Node *head1 = NULL, *head2 = NULL, *result = NULL;Â
    int arr1[] = { 9, 9, 9 };    int arr2[] = { 1, 8 };Â
    int size1 = sizeof(arr1) / sizeof(arr1[0]);    int size2 = sizeof(arr2) / sizeof(arr2[0]);Â
    // Create first list as 9->9->9    int i;    for (i = size1 - 1; i >= 0; --i)        push(&head1, arr1[i]);Â
    // Create second list as 1->8    for (i = size2 - 1; i >= 0; --i)        push(&head2, arr2[i]);Â
    addList(head1, head2, &result);Â
    printList(result);Â
    return 0;} |
Java
// A Java recursive program to add two linked listsÂ
public class linkedlistATN {    class node     {        int val;        node next;Â
        public node(int val)         {            this.val = val;        }    }         // Function to print linked list    void printlist(node head)     {        while (head != null)         {            System.out.print(head.val + " ");            head = head.next;        }    }Â
    node head1, head2, result;    int carry;Â
    /* A utility function to push a value to linked list */    void push(int val, int list)     {        node newnode = new node(val);        if (list == 1)         {            newnode.next = head1;            head1 = newnode;        }         else if (list == 2)         {            newnode.next = head2;            head2 = newnode;        }         else        {            newnode.next = result;            result = newnode;        }Â
    }Â
    // Adds two linked lists of same size represented by    // head1 and head2 and returns head of the resultant     // linked list. Carry is propagated while returning     // from the recursion    void addsamesize(node n, node m)     {        // Since the function assumes linked lists are of         // same size, check any of the two head pointers        if (n == null)            return;Â
        // Recursively add remaining nodes and get the carry        addsamesize(n.next, m.next);Â
        // add digits of current nodes and propagated carry        int sum = n.val + m.val + carry;        carry = sum / 10;        sum = sum % 10;Â
        // Push this to result list        push(sum, 3);Â
    }Â
    node cur;Â
    // This function is called after the smaller list is     // added to the bigger lists's sublist of same size.     // Once the right sublist is added, the carry must be     // added to the left side of larger list to get the     // final result.    void propogatecarry(node head1)     {        // If diff. number of nodes are not traversed, add carry        if (head1 != cur)         {            propogatecarry(head1.next);            int sum = carry + head1.val;            carry = sum / 10;            sum %= 10;Â
            // add this node to the front of the result            push(sum, 3);        }    }Â
    int getsize(node head)     {        int count = 0;        while (head != null)         {            count++;            head = head.next;        }        return count;    }Â
    // The main function that adds two linked lists     // represented by head1 and head2. The sum of two     // lists is stored in a list referred by result    void addlists()     {        // first list is empty        if (head1 == null)         {            result = head2;            return;        }Â
        // first list is empty        if (head2 == null)         {            result = head1;            return;        }Â
        int size1 = getsize(head1);        int size2 = getsize(head2);Â
        // Add same size lists        if (size1 == size2)         {            addsamesize(head1, head2);        }         else        {            // First list should always be larger than second list.            // If not, swap pointers            if (size1 < size2)             {                node temp = head1;                head1 = head2;                head2 = temp;            }            int diff = Math.abs(size1 - size2);Â
            // move diff. number of nodes in first list            node temp = head1;            while (diff-- >= 0)             {                cur = temp;                temp = temp.next;            }Â
            // get addition of same size lists            addsamesize(cur, head2);Â
            // get addition of remaining first list and carry            propogatecarry(head1);        }            // if some carry is still there, add a new node to             // the front of the result list. e.g. 999 and 87            if (carry > 0)                push(carry, 3);             }Â
    // Driver program to test above functions    public static void main(String args[])    {        linkedlistATN list = new linkedlistATN();        list.head1 = null;        list.head2 = null;        list.result = null;        list.carry = 0;        int arr1[] = { 9, 9, 9 };        int arr2[] = { 1, 8 };Â
        // Create first list as 9->9->9        for (int i = arr1.length - 1; i >= 0; --i)            list.push(arr1[i], 1);Â
        // Create second list as 1->8        for (int i = arr2.length - 1; i >= 0; --i)            list.push(arr2[i], 2);Â
        list.addlists();Â
        list.printlist(list.result);    }}Â
// This code is contributed by Rishabh Mahrsee |
Python3
# A Python3 recursive program to add two linked listsclass node:    def __init__(self, val):        self.val = val        self.next = NoneÂ
head1, head2, result = None, None, Nonecarry = 0Â
# Function to print linked listdef printlist(head):Â Â Â Â while head != None:Â Â Â Â Â Â Â Â print(head.val, end=" ")Â Â Â Â Â Â Â Â head = head.nextÂ
# A utility function to push a value to linked listdef push(val, lst):    global head1, head2, result    newnode = node(val)    if lst == 1:        newnode.next = head1        head1 = newnode    elif lst == 2:        newnode.next = head2        head2 = newnode    else:        newnode.next = result        result = newnodeÂ
# Adds two linked lists of same size represented by# head1 and head2 and returns head of the resultant# linked list. Carry is propagated while returning# from the recursiondef addsamesize(n, m):    global carry         # Since the function assumes linked lists are of    # same size, check any of the two head pointers    if n == None:        return           # Recursively add remaining nodes and get the carry    addsamesize(n.next, m.next)         # add digits of current nodes and propagated carry    sum = n.val + m.val + carry    carry = int(sum / 10)    sum = sum % 10         # Push this to result list    push(sum, 3)Â
cur = NoneÂ
# This function is called after the smaller list is# added to the bigger lists's sublist of same size.# Once the right sublist is added, the carry must be# added to the left side of larger list to get the# final result.def propogatecarry(head1):    global carry, cur         # If diff. number of nodes are not traversed, add carry    if head1 != cur:        propogatecarry(head1.next)        sum = carry + head1.val        carry = int(sum / 10)        sum %= 10                 # add this node to the front of the result        push(sum, 3)Â
def getsize(head):    count = 0    while head != None:        count += 1        head = head.next    return count   # The main function that adds two linked lists# represented by head1 and head2. The sum of two# lists is stored in a list referred by resultdef addlists():    global head1, head2, result, carry, cur         # first list is empty    if head1 == None:        result = head2        return           # first list is empty    if head2 == None:        result = head1        return    size1 = getsize(head1)    size2 = getsize(head2)         # Add same size lists    if size1 == size2:        addsamesize(head1, head2)    else:               # First list should always be larger than second list.        # If not, swap pointers        if size1 < size2:            temp = head1            head1 = head2            head2 = temp        diff = abs(size1 - size2)                 # move diff. number of nodes in first list        temp = head1        while diff >= 0:            cur = temp            temp = temp.next            diff -= 1                     # get addition of same size lists        addsamesize(cur, head2)                 # get addition of remaining first list and carry        propogatecarry(head1)             # if some carry is still there, add a new node to    # the front of the result list. e.g. 999 and 87    if carry > 0:        push(carry, 3)Â
# Driver program to test above functionshead1, head2, result = None, None, Nonecarry = 0arr1 = [9, 9, 9]arr2 = [1, 8]Â
# Create first list as 9->9->9for i in range(len(arr1)-1, -1, -1):Â Â Â Â push(arr1[i], 1)Â
# Create second list as 1->8for i in range(len(arr2)-1, -1, -1):Â Â Â Â push(arr2[i], 2)Â
addlists()printlist(result)Â
# This code is contributed by Prajwal Kandekar |
C#
// A C# recursive program to add two linked listsusing System;Â Â public class linkedlistATN{Â Â Â Â Â class node {Â Â Â Â public int val;Â Â Â Â public node next;Â
    public node(int val)     {        this.val = val;    }}  // Function to print linked listvoid printlist(node head) {    while (head != null)     {        Console.Write(head.val + " ");        head = head.next;    }}Â
node head1, head2, result;int carry;Â
// A utility function to push a // value to linked list void push(int val, int list) {    node newnode = new node(val);         if (list == 1)     {        newnode.next = head1;        head1 = newnode;    }     else if (list == 2)     {        newnode.next = head2;        head2 = newnode;    }     else    {        newnode.next = result;        result = newnode;    }Â
}Â
// Adds two linked lists of same size represented by// head1 and head2 and returns head of the resultant // linked list. Carry is propagated while returning // from the recursionvoid addsamesize(node n, node m) {         // Since the function assumes linked    // lists are of same size, check any    // of the two head pointers    if (n == null)        return;Â
    // Recursively add remaining nodes    // and get the carry    addsamesize(n.next, m.next);Â
    // Add digits of current nodes     // and propagated carry    int sum = n.val + m.val + carry;    carry = sum / 10;    sum = sum % 10;Â
    // Push this to result list    push(sum, 3);}Â
node cur;Â
// This function is called after the smaller // list is added to the bigger lists's sublist // of same size. Once the right sublist is added,// the carry must be added to the left side of // larger list to get the final result.void propogatecarry(node head1) {         // If diff. number of nodes are     // not traversed, add carry    if (head1 != cur)     {        propogatecarry(head1.next);        int sum = carry + head1.val;        carry = sum / 10;        sum %= 10;Â
        // Add this node to the front         // of the result        push(sum, 3);    }}Â
int getsize(node head) {Â Â Â Â int count = 0;Â Â Â Â while (head != null) Â Â Â Â {Â Â Â Â Â Â Â Â count++;Â Â Â Â Â Â Â Â head = head.next;Â Â Â Â }Â Â Â Â return count;}Â
// The main function that adds two linked // lists represented by head1 and head2. // The sum of two lists is stored in a // list referred by resultvoid addlists() {         // First list is empty    if (head1 == null)     {        result = head2;        return;    }Â
    // Second list is empty    if (head2 == null)     {        result = head1;        return;    }Â
    int size1 = getsize(head1);    int size2 = getsize(head2);Â
    // Add same size lists    if (size1 == size2)     {        addsamesize(head1, head2);    }     else    {                 // First list should always be        // larger than second list.        // If not, swap pointers        if (size1 < size2)         {            node temp = head1;            head1 = head2;            head2 = temp;        }                 int diff = Math.Abs(size1 - size2);Â
        // Move diff. number of nodes in        // first list        node tmp = head1;                 while (diff-- >= 0)         {            cur = tmp;            tmp = tmp.next;        }Â
        // Get addition of same size lists        addsamesize(cur, head2);Â
        // Get addition of remaining         // first list and carry        propogatecarry(head1);    }        // If some carry is still there,         // add a new node to the front of        // the result list. e.g. 999 and 87        if (carry > 0)            push(carry, 3);}Â
// Driver codepublic static void Main(string []args){Â Â Â Â linkedlistATN list = new linkedlistATN();Â Â Â Â list.head1 = null;Â Â Â Â list.head2 = null;Â Â Â Â list.result = null;Â Â Â Â list.carry = 0;Â Â Â Â Â Â Â Â Â int []arr1 = { 9, 9, 9 };Â Â Â Â int []arr2 = { 1, 8 };Â
    // Create first list as 9->9->9    for(int i = arr1.Length - 1; i >= 0; --i)        list.push(arr1[i], 1);Â
    // Create second list as 1->8    for(int i = arr2.Length - 1; i >= 0; --i)        list.push(arr2[i], 2);Â
    list.addlists();Â
    list.printlist(list.result);}}Â
// This code is contributed by rutvik_56 |
Javascript
<script>// A javascript recursive program to add two linked listsÂ
  class node {        constructor(val) {            this.val = val;            this.next = null;        }    }Â
    // Function to print linked list    function printlist( head) {        while (head != null) {            document.write(head.val + " ");            head = head.next;        }    }Â
    var head1, head2, result;    var carry;Â
    /* A utility function to push a value to linked list */    function push(val , list) {        var newnode = new node(val);        if (list == 1) {            newnode.next = head1;            head1 = newnode;        } else if (list == 2) {            newnode.next = head2;            head2 = newnode;        } else {            newnode.next = result;            result = newnode;        }Â
    }Â
    // Adds two linked lists of same size represented by    // head1 and head2 and returns head of the resultant    // linked list. Carry is propagated while returning    // from the recursion    function addsamesize( n, m) {        // Since the function assumes linked lists are of        // same size, check any of the two head pointers        if (n == null)            return;Â
        // Recursively add remaining nodes and get the carry        addsamesize(n.next, m.next);Â
        // add digits of current nodes and propagated carry        var sum = n.val + m.val + carry;        carry = parseInt(sum / 10);        sum = sum % 10;Â
        // Push this to result list        push(sum, 3);Â
    }Â
    var cur;Â
    // This function is called after the smaller list is    // added to the bigger lists's sublist of same size.    // Once the right sublist is added, the carry must be    // added to the left side of larger list to get the    // final result.    function propogatecarry( head1) {        // If diff. number of nodes are not traversed, add carry        if (head1 != cur) {            propogatecarry(head1.next);            var sum = carry + head1.val;            carry = parseInt(sum / 10);            sum %= 10;Â
            // add this node to the front of the result            push(sum, 3);        }    }Â
    function getsize( head) {        var count = 0;        while (head != null) {            count++;            head = head.next;        }        return count;    }Â
    // The main function that adds two linked lists    // represented by head1 and head2. The sum of two    // lists is stored in a list referred by result    function addlists() {        // first list is empty        if (head1 == null) {            result = head2;            return;        }Â
        // first list is empty        if (head2 == null) {            result = head1;            return;        }Â
        var size1 = getsize(head1);        var size2 = getsize(head2);Â
        // Add same size lists        if (size1 == size2) {            addsamesize(head1, head2);        } else {            // First list should always be larger than second list.            // If not, swap pointers            if (size1 < size2) {                var temp = head1;                head1 = head2;                head2 = temp;            }            var diff = Math.abs(size1 - size2);Â
            // move diff. number of nodes in first list            var temp = head1;            while (diff-- >= 0) {                cur = temp;                temp = temp.next;            }Â
            // get addition of same size lists            addsamesize(cur, head2);Â
            // get addition of remaining first list and carry            propogatecarry(head1);        }        // if some carry is still there, add a new node to        // the front of the result list. e.g. 999 and 87        if (carry > 0)            push(carry, 3);Â
    }Â
    // Driver program to test above functions             head1 = null;        head2 = null;        result = null;        carry = 0;        var arr1 = [ 9, 9, 9 ];        var arr2 = [ 1, 8 ];Â
        // Create first list as 9->9->9        for (i = arr1.length - 1; i >= 0; --i)            push(arr1[i], 1);Â
        // Create second list as 1->8        for (i = arr2.length - 1; i >= 0; --i)            push(arr2[i], 2);Â
        addlists();Â
        printlist(result);Â
// This code is contributed by todaysgaurav</script> |
1 0 1 7
Time Complexity: O(m+n) where m and n are the sizes of given two linked lists.
Auxiliary Space: O(m+n) for call stack
Iterative Approach:
This implementation does not have any recursion call overhead, which means it is an iterative solution.
Since we need to start adding numbers from the last of the two linked lists. So, here we will use the stack data structure to implement this.
- We will firstly make two stacks from the given two linked lists.
- Then, we will run a loop till both stack become empty.
- in every iteration, we keep the track of the carry.
- In the end, if carry>0, that means we need extra node at the start of the resultant list to accommodate this carry.
Below is the implementation of the above approach.Â
C++
// C++ Iterative program to add two linked lists #include <bits/stdc++.h> using namespace std;    // A linked List Node class Node {     public:     int data;     Node* next; };Â
// to push a new node to linked listvoid push(Node** head_ref, int new_data)Â {Â Â Â Â Â /* allocate node */Â Â Â Â Node* new_node = new Node[(sizeof(Node))];Â Â Â Â Â Â Â Â /* put in the data */Â Â Â Â new_node->data = new_data;Â Â Â Â Â Â Â Â /* link the old list of the new node */Â Â Â Â new_node->next = (*head_ref);Â Â Â Â Â Â Â Â /* move the head to point to the new node */Â Â Â Â (*head_ref) = new_node;Â }Â
// to add two new numbersNode* addTwoNumList(Node* l1, Node* l2) {Â Â Â Â stack<int> s1,s2;Â Â Â Â while(l1!=NULL){Â Â Â Â Â Â Â Â s1.push(l1->data);Â Â Â Â Â Â Â Â l1=l1->next;Â Â Â Â }Â Â Â Â while(l2!=NULL){Â Â Â Â Â Â Â Â s2.push(l2->data);Â Â Â Â Â Â Â Â l2=l2->next;Â Â Â Â }Â Â Â Â int carry=0;Â Â Â Â Node* result=NULL;Â Â Â Â while(s1.empty()==false || s2.empty()==false){Â Â Â Â Â Â Â Â int a=0,b=0;Â Â Â Â Â Â Â Â if(s1.empty()==false){Â Â Â Â Â Â Â Â Â Â Â Â a=s1.top();s1.pop();Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â if(s2.empty()==false){Â Â Â Â Â Â Â Â Â Â Â Â b=s2.top();s2.pop();Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â int total=a+b+carry;Â Â Â Â Â Â Â Â Node* temp=new Node();Â Â Â Â Â Â Â Â temp->data=total%10;Â Â Â Â Â Â Â Â carry=total/10;Â Â Â Â Â Â Â Â if(result==NULL){Â Â Â Â Â Â Â Â Â Â Â Â result=temp;Â Â Â Â Â Â Â Â }else{Â Â Â Â Â Â Â Â Â Â Â Â temp->next=result;Â Â Â Â Â Â Â Â Â Â Â Â result=temp;Â Â Â Â Â Â Â Â }Â Â Â Â }Â Â Â Â if(carry!=0){Â Â Â Â Â Â Â Â Node* temp=new Node();Â Â Â Â Â Â Â Â temp->data=carry;Â Â Â Â Â Â Â Â temp->next=result;Â Â Â Â Â Â Â Â result=temp;Â Â Â Â }Â Â Â Â return result;}Â
// to print a linked listvoid printList(Node *node)Â {Â Â Â Â Â while (node != NULL)Â Â Â Â Â {Â Â Â Â Â Â Â Â Â cout<<node->data<<" ";Â Â Â Â Â Â Â Â Â node = node->next;Â Â Â Â Â }Â Â Â Â Â cout<<endl;Â }Â
// Driver Codeint main()Â {Â Â Â Â Â Node *head1 = NULL, *head2 = NULL;Â Â Â Â Â Â Â Â int arr1[] = {5, 6, 7};Â Â Â Â Â int arr2[] = {1, 8};Â Â Â Â Â Â Â Â int size1 = sizeof(arr1) / sizeof(arr1[0]);Â Â Â Â Â int size2 = sizeof(arr2) / sizeof(arr2[0]);Â Â Â Â Â Â Â Â // Create first list as 5->6->7Â Â Â Â Â int i;Â Â Â Â Â for (i = size1-1; i >= 0; --i)Â Â Â Â Â Â Â Â Â push(&head1, arr1[i]);Â Â Â Â Â Â Â Â // Create second list as 1->8Â Â Â Â Â for (i = size2-1; i >= 0; --i)Â Â Â Â Â Â Â Â Â push(&head2, arr2[i]);Â Â Â Â Â Â Â Â Â Â Node* result=addTwoNumList(head1, head2);Â Â Â Â printList(result);Â Â Â Â Â Â Â Â return 0;Â } |
Java
// Java Iterative program to add // two linked lists import java.io.*;import java.util.*;Â
class GFG{Â Â Â Â Â static class Node{Â Â Â Â int data;Â Â Â Â Node next;Â Â Â Â Â Â Â Â Â public Node(int data)Â Â Â Â { Â Â Â Â Â Â Â Â this.data = data;Â Â Â Â }}Â
static Node l1, l2, result;Â
// To push a new node to linked listpublic static void push(int new_data){         // Allocate node     Node new_node = new Node(0);Â
    // Put in the data     new_node.data = new_data;Â
    // Link the old list of the new node     new_node.next = l1;Â
    // Move the head to point to the new node     l1 = new_node;}Â
public static void push1(int new_data){         // Allocate node     Node new_node = new Node(0);Â
    // Put in the data     new_node.data = new_data;Â
    // Link the old list of the new node     new_node.next = l2;Â
    // Move the head to point to    // the new node     l2 = new_node;}Â
// To add two new numberspublic static Node addTwoNumbers(){Â Â Â Â Stack<Integer> stack1 = new Stack<>();Â Â Â Â Stack<Integer> stack2 = new Stack<>();Â
    while (l1 != null)    {        stack1.add(l1.data);        l1 = l1.next;    }Â
    while (l2 != null)     {        stack2.add(l2.data);        l2 = l2.next;    }Â
    int carry = 0;    Node result = null;Â
    while (!stack1.isEmpty() ||           !stack2.isEmpty())     {        int a = 0, b = 0;Â
        if (!stack1.isEmpty())         {            a = stack1.pop();        }Â
        if (!stack2.isEmpty())         {            b = stack2.pop();        }Â
        int total = a + b + carry;Â
        Node temp = new Node(total % 10);        carry = total / 10;Â
        if (result == null)         {            result = temp;        }        else        {            temp.next = result;            result = temp;        }    }Â
    if (carry != 0)    {        Node temp = new Node(carry);        temp.next = result;        result = temp;    }    return result;}Â
// To print a linked listpublic static void printList(){Â Â Â Â while (result != null) Â Â Â Â {Â Â Â Â Â Â Â Â System.out.print(result.data + " ");Â Â Â Â Â Â Â Â result = result.next;Â Â Â Â }Â Â Â Â System.out.println();}Â
// Driver codepublic static void main(String[] args){Â Â Â Â int arr1[] = { 5, 6, 7 };Â Â Â Â int arr2[] = { 1, 8 };Â
    int size1 = 3;    int size2 = 2;Â
    // Create first list as 5->6->7    int i;    for(i = size1 - 1; i >= 0; --i)        push(arr1[i]);Â
    // Create second list as 1->8    for(i = size2 - 1; i >= 0; --i)        push1(arr2[i]);Â
    result = addTwoNumbers();Â
    printList();}}Â
// This code is contributed by RohitOberoi |
Python3
# Python Iterative program to add# two linked lists   class Node:    def __init__(self,val):        self.data = val        self.next = None     l1, l2, result = None,None,0Â
# To push a new node to linked listdef push(new_data):Â
    global l1Â
    # Allocate node    new_node = Node(0)Â
    # Put in the data    new_node.data = new_dataÂ
    # Link the old list of the new node    new_node.next = l1Â
    # Move the head to point to the new node    l1 = new_nodeÂ
Â
def push1(new_data):Â
    global l2Â
    # Allocate node    new_node = Node(0)Â
    # Put in the data    new_node.data = new_dataÂ
    # Link the old list of the new node    new_node.next = l2Â
    # Move the head to point to    # the new node    l2 = new_nodeÂ
# To add two new numbersdef addTwoNumbers():Â
    global l1,l2,resultÂ
    stack1 = []    stack2 = []Â
    while (l1 != None):        stack1.append(l1.data)        l1 = l1.nextÂ
    while (l2 != None):        stack2.append(l2.data)        l2 = l2.nextÂ
    carry = 0    result = NoneÂ
    while (len(stack1) != 0 or len(stack2) != 0):        a,b = 0,0Â
        if (len(stack1) != 0):            a = stack1.pop()Â
        if (len(stack2) != 0):            b = stack2.pop()Â
        total = a + b + carryÂ
        temp = Node(total % 10)        carry = total // 10Â
        if (result == None):            result = temp        else:            temp.next = result            result = tempÂ
Â
    if (carry != 0):        temp = Node(carry)        temp.next = result        result = temp             return resultÂ
Â
# To print a linked listdef printList():Â
    global resultÂ
    while (result != None):        print(result.data ,end = " ")        result = result.nextÂ
# Driver code     arr1 = [ 5, 6, 7 ]arr2 = [ 1, 8 ]Â
size1 = 3size2 = 2Â
# Create first list as 5->6->7Â
for i in range(size1-1,-1,-1):Â Â Â Â push(arr1[i])Â
# Create second list as 1->8for i in range(size2-1,-1,-1):Â Â Â Â push1(arr2[i])Â
result = addTwoNumbers()Â
printList()Â
# This code is contributed by shinjanpatra |
C#
// C# Iterative program to add // two linked lists using System;using System.Collections;Â
class GFG{Â
  public class Node  {    public int data;    public Node next;Â
    public Node(int data)    {       this.data = data;    }  }Â
  static Node l1, l2, result;Â
  // To push a new node to linked list  public static void push(int new_data)  {Â
    // Allocate node     Node new_node = new Node(0);Â
    // Put in the data     new_node.data = new_data;Â
    // Link the old list of the new node     new_node.next = l1;Â
    // Move the head to point to the new node     l1 = new_node;  }Â
  public static void push1(int new_data)  {Â
    // Allocate node     Node new_node = new Node(0);Â
    // Put in the data     new_node.data = new_data;Â
    // Link the old list of the new node     new_node.next = l2;Â
    // Move the head to point to    // the new node     l2 = new_node;  }Â
  // To add two new numbers  public static Node addTwoNumbers()  {    Stack stack1 = new Stack();    Stack stack2 = new Stack();Â
    while (l1 != null)    {      stack1.Push(l1.data);      l1 = l1.next;    }    while (l2 != null)     {      stack2.Push(l2.data);      l2 = l2.next;    }Â
    int carry = 0;    Node result = null;    while (stack1.Count != 0 ||           stack2.Count != 0)     {      int a = 0, b = 0;Â
      if (stack1.Count != 0)       {        a = (int)stack1.Pop();      }Â
      if (stack2.Count != 0)       {        b = (int)stack2.Pop();      }Â
      int total = a + b + carry;      Node temp = new Node(total % 10);      carry = total / 10;Â
      if (result == null)       {        result = temp;      }      else      {        temp.next = result;        result = temp;      }    }Â
    if (carry != 0)    {      Node temp = new Node(carry);      temp.next = result;      result = temp;    }    return result;  }Â
  // To print a linked list  public static void printList()  {    while (result != null)     {      Console.Write(result.data + " ");      result = result.next;    }    Console.WriteLine();  }Â
  // Driver code  public static void Main(string[] args)  {    int []arr1 = { 5, 6, 7 };    int []arr2 = { 1, 8 };    int size1 = 3;    int size2 = 2;Â
    // Create first list as 5->6->7    int i;    for(i = size1 - 1; i >= 0; --i)      push(arr1[i]);Â
    // Create second list as 1->8    for(i = size2 - 1; i >= 0; --i)      push1(arr2[i]);    result = addTwoNumbers();    printList();  }}Â
// This code is contributed by pratham76 |
Javascript
<script>// javascript Iterative program to add // two linked lists      class Node {    constructor(val) {        this.data = val;        this.next = null;    }}    var l1, l2, result;Â
    // To push a new node to linked list    function push(new_data) {Â
        // Allocate nodevar new_node = new Node(0);Â
        // Put in the data        new_node.data = new_data;Â
        // Link the old list of the new node        new_node.next = l1;Â
        // Move the head to point to the new node        l1 = new_node;    }Â
    function push1(new_data) {Â
        // Allocate nodevar new_node = new Node(0);Â
        // Put in the data        new_node.data = new_data;Â
        // Link the old list of the new node        new_node.next = l2;Â
        // Move the head to point to        // the new node        l2 = new_node;    }Â
    // To add two new numbers    function addTwoNumbers() {        var stack1 = [];        var stack2 = [];Â
        while (l1 != null) {            stack1.push(l1.data);            l1 = l1.next;        }Â
        while (l2 != null) {            stack2.push(l2.data);            l2 = l2.next;        }Â
        var carry = 0;var result = null;Â
        while (stack1.length != 0 || stack2.length != 0) {            var a = 0, b = 0;Â
            if (stack1.length != 0) {                a = stack1.pop();            }Â
            if (stack2.length != 0) {                b = stack2.pop();            }Â
            var total = a + b + carry;Â
    var temp = new Node(total % 10);            carry = parseInt(total / 10);Â
            if (result == null) {                result = temp;            } else {                temp.next = result;                result = temp;            }        }Â
        if (carry != 0) {    var temp = new Node(carry);            temp.next = result;            result = temp;        }        return result;    }Â
    // To print a linked list    function printList() {        while (result != null) {            document.write(result.data + " ");            result = result.next;        }        document.write();    }Â
    // Driver code             var arr1 = [ 5, 6, 7 ];        var arr2 = [ 1, 8 ];Â
        var size1 = 3;        var size2 = 2;Â
        // Create first list as 5->6->7        var i;        for (var i = size1 - 1; i >= 0; --i)            push(arr1[i]);Â
        // Create second list as 1->8        for (i = size2 - 1; i >= 0; --i)            push1(arr2[i]);Â
        result = addTwoNumbers();Â
        printList();Â
// This code contributed by umadevi9616 </script> |
5 8 5
Time Complexity: O(m+n) where m and n are the sizes of given two linked lists.
Auxiliary Space: O(m+n)
Another Approach (Simple iteration with 2 pointers)
To add two numbers in a linked list, we can simply iterate the 2 linked lists and take the sum of the values in nodes along with maintaining a carry. While taking sums add the previous carry to it and add a new node to the result containing the last digit in the sum and update the carry for the next iteration.
Algorithm :
- Use 2 pointers to store the head of each linked list and initialize carry as 0.
- Declare a pointer to the node to store our answer.
- Iterate through both the linked list and add the digits pointed by the pointers (if we have reached the end of one of the linked lists and have no further nodes, consider its value as 0 while taking the sum).
- Add a new node with ((sum+carry)%10) as value to our answer and update carry as (sum + carry)/10.
- Repeat steps 3 and 4 till we reach the end of both the linked lists.
- After traversing both the linked lists, if carry > 0 then add this carry to our answer as a new node.
C++
#include<bits/stdc++.h>using namespace std;Â
struct Node {Â Â Â Â int val;Â Â Â Â Node* next;Â
    Node(int value){        val = value;        next = NULL;    }};Â
void push_front(Node** head, int new_val){Â Â Â Â Node* new_node = new Node(new_val);Â Â Â Â new_node->next = *head;Â Â Â Â *head = new_node;}Â
void printList(Node* head){Â Â Â Â Node* i = head;Â Â Â Â while(i){Â Â Â Â Â Â Â Â cout<<i->val<<" ";Â Â Â Â Â Â Â Â i = i->next;Â Â Â Â }Â Â Â Â cout<<"\n";}Â
// function to add 2 numbers given as linked listsNode* add(Node* l1, Node* l2){Â Â Â Â Node* ans = new Node(0);Â Â Â Â Node* curr = ans;Â Â Â Â int carry = 0;Â Â Â Â while(l1 || l2){Â Â Â Â Â Â Â Â int sum = 0;Â Â Â Â Â Â Â Â if(l1) sum += l1->val;Â Â Â Â Â Â Â Â if(l2) sum += l2->val;Â Â Â Â Â Â Â Â sum += carry;Â
        curr->next = new Node(sum%10);        curr = curr->next;Â
        carry = sum/10;Â
        if(l1) l1 = l1->next;        if(l2) l2 = l2->next;    }Â
    if(carry){        curr->next = new Node(carry);    }    ans = ans->next;    return ans;}Â
int main(){Â Â Â Â Node* l1 = NULL;Â
    push_front(&l1, 1);    push_front(&l1, 5);Â
    Node* l2 = NULL;Â
    push_front(&l2, 3);    push_front(&l2, 9);    push_front(&l2, 7);Â
    // l1-> 5 1  = 15    // l2-> 7 9 3 = 397Â
    Node* sum = add(l1,l2);Â
    printList(sum);    // 2 1 4     = 412} |
Java
/*package whatever //do not write package name here */Â
class Node {    int val;    Node next;    Node(int value)    {        val = value;        next = null;    }}class AddTwoLL {    static void push_front(Node head, int new_val)    {        Node new_node = new Node(new_val);        new_node.next =head;        head = new_node;    }    static void printList(Node head)    {        Node i = head;        while(i!=null)        {            System.out.print(i.val+" ");            i = i.next;        }        System.out.println();    }    // function to reverse a linked list    static Node reverse_it(Node head)    {        Node prev = null;        Node curr = head, next;        while(curr!=null)        {            next = curr.next;            curr.next = prev;            prev = curr;            curr = next;        }        return prev;    }    // function to convert a linked list to integer    static int to_integer(Node head){        int num = 0;        Node curr = head;        while(curr!=null)        {            int digit = curr.val;            num = num*10 + digit;            curr = curr.next;        }        return num;    }    // function to convert a number to a linked list containing digits in reverse order    static Node to_linkedlist(int x)    {        Node head = new Node(0);        if(x==0) return head;        Node curr = head;        while(x>0)        {            int d = x%10;            x /= 10;            curr.next = new Node(d);            curr = curr.next;        }        return head.next;    }    // function to add 2 numbers given as linked lists    static Node add_list(Node l1, Node l2)    {        // reversing the 2 linked lists        l1 = reverse_it(l1);        l2 = reverse_it(l2);             // converting them into integers        int num1 = to_integer(l1);        int num2 = to_integer(l2);                 int sum = num1 + num2;        // converting the sum back to        // a linked list        Node ans = to_linkedlist(sum);                 return ans;    }    public static void main(String [] args)    {        Node l1 = null;             push_front(l1, 1);        push_front(l1, 5);             Node l2 = null;             push_front(l2, 3);        push_front(l2, 9);        push_front(l2, 7);             // l1-> 5 1        // l2-> 7 9 3             Node sum = add_list(l1,l2);             printList(sum);        // 2 1 4    }} |
Python3
# Add two numbers represented by linked lists | Set 2class Node:    def __init__(self, value):        self.val = value        self.next = NoneÂ
Â
def push_front(head, new_val):    new_node = Node(new_val)    new_node.next = head    head = new_node    return headÂ
Â
def print_list(head):    i = head    while i:        print(i.val, end=" ")        i = i.next    print()Â
Â
def add(l1, l2):    ans = Node(0)    curr = ans    carry = 0Â
    while l1 or l2:        sum_val = 0        if l1:            sum_val += l1.val            l1 = l1.next        if l2:            sum_val += l2.val            l2 = l2.next        sum_val += carryÂ
        curr.next = Node(sum_val % 10)        curr = curr.next        carry = sum_val // 10Â
    if carry:        curr.next = Node(carry)Â
    ans = ans.next    return ansÂ
Â
# Creating linked list l1: 5 -> 1l1 = Nonel1 = push_front(l1, 1)l1 = push_front(l1, 5)Â
# Creating linked list l2: 7 -> 9 -> 3l2 = Nonel2 = push_front(l2, 3)l2 = push_front(l2, 9)l2 = push_front(l2, 7)Â
# l1: 5 -> 1Â Â =Â 15# l2: 7 -> 9 -> 3 = 397Â
# Adding two linked listssum_list = add(l1, l2)Â
# Printing the resulting linked listprint_list(sum_list)# Output: 2 1 4Â Â = 412Â
# This code is contributed by uomkar369 |
2 1 4
Time Complexity: O(n).
Space Complexity:Â O(max(n,m))
To avoid the use of extra space we can store the sum in one of the linked lists itself.
Related Article: Add two numbers represented by linked lists | Set 1
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



