Open In App

Add Two Numbers Represented as Linked List

Last Updated : 21 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two numbers represented as two lists, the task is to return the sum of two lists.

Note: There can be leading zeros in the input lists, but there should not be any leading zeros in the output list.

Examples:

Input: num1 = 4 -> 5, num2 = 3 -> 4 -> 5
Output: 3 -> 9 -> 0 
Explanation: Sum of 45 and 345 is 390.

Add-two-numbers-represented-by-linked-lists-

Add two numbers represented by Linked List


Input: num1 = 0 -> 0 -> 6 -> 3, num2 = 0 -> 7
Output: 7 -> 0
Explanation: Sum of 63 and 7 is 70.

Input: num1 = 1 -> 2 -> 3, num2 = 9 -> 9 -> 9
Output: 1 -> 1 -> 2 -> 2
Explanation: Sum of 123 and 999 = 1122.

[Naive Approach] By creating a new list – O(m + n) Time and O(max(m, n)) Space

To sum two linked lists, start by creating an empty linked list, say result, for the sum. Reverse both original linked lists to start from the least significant digit.

Use two pointers to traverse the reversed lists simultaneously. For each pair of nodes, compute their sum and if the sum exceeds 9, store the remainder(sum modulo 10) in the new node and forward the carry to the next pair of nodes. Append each new node to result.

Continue until both lists are fully traversed, handling any remaining nodes from the longer list and carrying over any final carry. Finally, reverse the result linked list to get the sum of the two linked list.

C++
//Driver Code Starts{
// C++ Program to add two number represented as
// linked list by creating a new list

#include <iostream>
using namespace std;

class Node {
  public:
    int data;
    Node *next;
    Node(int val) {
        data = val;
        next = nullptr;
    }
};
//Driver Code Ends }


// Function to reverse the linked list
Node *reverse(Node *head) {
    Node *prev = nullptr, *curr = head, *next;

    while (curr != nullptr) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}

// Function to trim leading zeros in linked list
Node *trimLeadingZeros(Node* head) {
	while(head->next != nullptr && head->data == 0)
    	head = head->next;
	return head;
}

// Function to add two numbers represented by linked list
Node *addTwoLists(Node *num1, Node *num2) {
    Node *res = nullptr, *curr = nullptr;
    int carry = 0;

	num1 = trimLeadingZeros(num1);
	num2 = trimLeadingZeros(num2);
  
    num1 = reverse(num1);
    num2 = reverse(num2);

    // Iterate till either num1 is not empty or num2 is
    // not empty or carry is greater than 0
    while (num1 != nullptr || num2 != nullptr || carry != 0) {
        int sum = carry;

        // If num1 linked list is not empty, add it to sum
        if (num1 != nullptr) {
            sum += num1->data;
            num1 = num1->next;
        }

        // If num2 linked list is not empty, add it to sum
        if (num2 != nullptr) {
            sum += num2->data;
            num2 = num2->next;
        }
      
      	// Create a new node with sum % 10 as its value
        Node* newNode = new Node(sum % 10);

        // Store the carry for the next nodes
        carry = sum / 10;

      	// If this is the first node, then make this node
      	// as the head of the resultant linked list
      	if(res == nullptr) {
        	res = newNode;
          	curr = newNode;
        }
      	else {
          	
          	// Append new node to resultant linked list
          	// and move to the next node
        	curr->next = newNode;
        	curr = curr->next;
        }
    }

    // Reverse the resultant linked list to get the
    // required linked list
    return reverse(res);
}


//Driver Code Starts{
void printList(Node *head) {
    Node *curr = head;
    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << "
";
}

int main() {

    // Creating first linked list: 1 -> 2 -> 3
    // (represents 123)
    Node *num1 = new Node(1);
    num1->next = new Node(2);
    num1->next->next = new Node(3);

    // Creating second linked list: 9 -> 9 -> 9
    // (represents 999)
    Node *num2 = new Node(9);
    num2->next = new Node(9);
    num2->next->next = new Node(9);

    Node *sum = addTwoLists(num1, num2);
    printList(sum);

    return 0;
}
//Driver Code Ends }
C
//Driver Code Starts{
// C Program to add two number represented as
// linked list by creating a new list

#include <stdio.h>

struct Node {
    int data;
    struct Node *next;
};

struct Node *createNode(int val);
//Driver Code Ends }


// Function to reverse the linked list
struct Node *reverse(struct Node *head) {
    struct Node *prev = NULL, *curr = head, *next;

    while (curr != NULL) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}

// Function to trim leading zeros in linked list
struct Node* trimLeadingZeros(struct Node* head) {
    while (head->next != NULL && head->data == 0)
        head = head->next;
    return head;
}

// Function to add two numbers represented by linked list
struct Node *addTwoLists(struct Node *num1, struct Node *num2) {
    struct Node *res = NULL, *curr = NULL;
    int carry = 0;
  
	num1 = trimLeadingZeros(num1);
	num2 = trimLeadingZeros(num2);
  
    num1 = reverse(num1);
    num2 = reverse(num2);

    // Iterate till either num1 is not empty or num2 is
    // not empty or carry is greater than 0
    while (num1 != NULL || num2 != NULL || carry != 0) {
        int sum = carry;

        // If num1 linked list is not empty, add it to sum
        if (num1 != NULL) {
            sum += num1->data;
            num1 = num1->next;
        }

        // If num2 linked list is not empty, add it to sum
        if (num2 != NULL) {
            sum += num2->data;
            num2 = num2->next;
        }
      
        // Create a new node with sum % 10 as its value
        struct Node* newNode = createNode(sum % 10);

        // Store the carry for the next nodes
        carry = sum / 10;

        // If this is the first node, then make this node
        // as the head of the resultant linked list
        if (res == NULL) {
            res = newNode;
            curr = newNode;
        } 
      	else {
            
          	// Append new node to resultant linked list
            // and move to the next node
            curr->next = newNode;
            curr = curr->next;
        }
    }

    // Reverse the resultant linked list to get the
    // required linked list
    return reverse(res);
}


//Driver Code Starts{
void printList(struct Node *head) {
    struct Node *curr = head;
    while (curr != NULL) {
        printf("%d ", curr->data);
        curr = curr->next;
    }
    printf("
");
}

struct Node *createNode(int val) {
    struct Node *node = 
      		(struct Node *)malloc(sizeof(struct Node));
    node->data = val;
    node->next = NULL;
    return node;
}

int main() {

    // Creating first linked list: 1 -> 2 -> 3
    // (represents 123)
    struct Node *num1 = createNode(1);
    num1->next = createNode(2);
    num1->next->next = createNode(3);

    // Creating second linked list: 9 -> 9 -> 9
    // (represents 999)
    struct Node *num2 = createNode(9);
    num2->next = createNode(9);
    num2->next->next = createNode(9);

    struct Node *sum = addTwoLists(num1, num2);
    printList(sum);

    return 0;
}
//Driver Code Ends }
Java
//Driver Code Starts{
// Java Program to add two numbers represented as
// linked list by creating a new list

class Node {
    int data;
    Node next;

    Node(int val) {
        data = val;
        next = null;
    }
}

class GfG {
//Driver Code Ends }


    // Function to reverse the linked list
    static Node reverse(Node head) {
        Node prev = null;
        Node curr = head;
        Node next;

        while (curr != null) {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
	
	// Function to trim leading zeros in linked list
	static Node trimLeadingZeros(Node head) {
        while (head != null && head.data == 0) {
            head = head.next;
        }
        return head;
    }

    // Function to add two numbers represented by linked list
    static Node addTwoLists(Node num1, Node num2) {
        Node res = null;
        Node curr = null;
        int carry = 0;
      
		num1 = trimLeadingZeros(num1);
		num2 = trimLeadingZeros(num2);
      
        num1 = reverse(num1);
        num2 = reverse(num2);

        // Iterate till either num1 is not empty or num2 is
        // not empty or carry is greater than 0
        while (num1 != null || num2 != null || carry != 0) {
            int sum = carry;

            // If num1 linked list is not empty, add it to sum
            if (num1 != null) {
                sum += num1.data;
                num1 = num1.next;
            }

            // If num2 linked list is not empty, add it to sum
            if (num2 != null) {
                sum += num2.data;
                num2 = num2.next;
            }
          
            // Create a new node with sum % 10 as its value
            Node newNode = new Node(sum % 10);

            // Store the carry for the next nodes
            carry = sum / 10;

            // If this is the first node, then make this node
            // as the head of the resultant linked list
            if (res == null) {
                res = newNode;
                curr = newNode;
            } else {
                // Append new node to resultant linked list
                // and move to the next node
                curr.next = newNode;
                curr = curr.next;
            }
        }

        // Reverse the resultant linked list to get the
        // required linked list
        return reverse(res);
    }


//Driver Code Starts{
    static void printList(Node head) {
        Node curr = head;
        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        
      	// Creating first linked list: 1 -> 2 -> 3
        // (represents 123)
        Node num1 = new Node(1);
        num1.next = new Node(2);
        num1.next.next = new Node(3);

        // Creating second linked list: 9 -> 9 -> 9
        // (represents 999)
        Node num2 = new Node(9);
        num2.next = new Node(9);
        num2.next.next = new Node(9);

        Node sum = addTwoLists(num1, num2);
        printList(sum);
    }
}

//Driver Code Ends }
Python
#Driver Code Starts{
# Python Program to add two number represented as
# linked list by creating a new list

class Node:
    def __init__(self, val):
        self.data = val
        self.next = None
#Driver Code Ends }


# function to reverse the linked list
def reverse(head):
    prev = None
    curr = head

    while curr is not None:
        nextNode = curr.next
        curr.next = prev
        prev = curr
        curr = nextNode

    return prev

# function to trim leading zeros in linked list
def trimLeadingZeros(head):
    while head and head.data == 0:
        head = head.next
    return head

# Function to add two numbers represented by linked list
def addTwoLists(num1, num2):
    res = None
    curr = None
    carry = 0

    num1 = trimLeadingZeros(num1)
    num2 = trimLeadingZeros(num2)
    
    num1 = reverse(num1)
    num2 = reverse(num2)

    # Iterate till either num1 is not empty or num2 is
    # not empty or carry is greater than 0
    while num1 is not None or num2 is not None or carry != 0:
        sumValue = carry

        # If num1 linked list is not empty, add it to sum
        if num1 is not None:
            sumValue += num1.data
            num1 = num1.next

        # If num2 linked list is not empty, add it to sum
        if num2 is not None:
            sumValue += num2.data
            num2 = num2.next
        
        # Create a new node with sum % 10 as its value
        newNode = Node(sumValue % 10)

        # Store the carry for the next nodes
        carry = sumValue // 10

        # If this is the first node, then make this node
        # as the head of the resultant linked list
        if res is None:
            res = newNode
            curr = newNode
        else:
            # Append new node to resultant linked list
            # and move to the next node
            curr.next = newNode
            curr = curr.next

    # Reverse the resultant linked list to get the
    # required linked list
    return reverse(res)


#Driver Code Starts{
def printList(head):
    curr = head
    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.next
    print()

if __name__ == "__main__":
    
    # Creating first linked list: 1 -> 2 -> 3
    # (represents 123)
    num1 = Node(1)
    num1.next = Node(2)
    num1.next.next = Node(3)

    # Creating second linked list: 9 -> 9 -> 9
    # (represents 999)
    num2 = Node(9)
    num2.next = Node(9)
    num2.next.next = Node(9)

    sumList = addTwoLists(num1, num2)
    printList(sumList)

#Driver Code Ends }
C#
//Driver Code Starts{
// C# Program to add two number represented as
// linked list by creating a new list

using System;

class Node {
    public int data;
    public Node next;

    public Node(int val) {
        data = val;
        next = null;
    }
}

class GfG {
//Driver Code Ends }

    
  	// Function to reverse the linked list
    static Node Reverse(Node head) {
        Node prev = null;
        Node curr = head;
        Node next;

        while (curr != null) {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
	
	// function to trim leading zeros in linked list
    static Node TrimLeadingZeros(Node head) {
        while (head != null && head.data == 0) {
            head = head.next;
        }
        return head;
    }
  
    // Function to add two numbers represented by linked list
    static Node AddTwoLists(Node num1, Node num2) {
    	Node res = null;
        Node curr = null;
        int carry = 0;

		num1 = TrimLeadingZeros(num1);
		num2 = TrimLeadingZeros(num2);
      
        num1 = Reverse(num1);
        num2 = Reverse(num2);

        // Iterate till either num1 is not empty or num2 is
        // not empty or carry is greater than 0
        while (num1 != null || num2 != null || carry != 0) {
            int sum = carry;

            // If num1 linked list is not empty, add it to sum
            if (num1 != null) {
                sum += num1.data;
                num1 = num1.next;
            }

            // If num2 linked list is not empty, add it to sum
            if (num2 != null) {
                sum += num2.data;
                num2 = num2.next;
            }

            // Create a new node with sum % 10 as its value
            Node newNode = new Node(sum % 10);

            // Store the carry for the next nodes
            carry = sum / 10;

            // If this is the first node, then make this node
            // as the head of the resultant linked list
            if (res == null) {
                res = newNode;
                curr = newNode;
            }
            else {
              
                // Append new node to resultant linked list
                // and move to the next node
                curr.next = newNode;
                curr = curr.next;
            }
        }

        // Reverse the resultant linked list to get the
        // required linked list
        return Reverse(res);
    }


//Driver Code Starts{
    static void PrintList(Node head) {
        Node curr = head;
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.next;
        }
        Console.WriteLine();
    }

    static void Main() {
        
      	// Creating first linked list: 1 -> 2 -> 3
        // (represents 123)
        Node num1 = new Node(1);
        num1.next = new Node(2);
        num1.next.next = new Node(3);

        // Creating second linked list: 9 -> 9 -> 9
        // (represents 999)
        Node num2 = new Node(9);
        num2.next = new Node(9);
        num2.next.next = new Node(9);

        Node sum = AddTwoLists(num1, num2);
        PrintList(sum);
    }
}

//Driver Code Ends }
JavaScript
//Driver Code Starts{
// JavaScript Program to add two number represented
// as linked list by creating a new list

class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
    }
}
//Driver Code Ends }


// Function to reverse the linked list
function reverse(head) {
    let prev = null;
    let curr = head;
    let next;

    while (curr !== null) {
        next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}

// function to trim leading zeros in linked list
function trimLeadingZeros(head) {
    while (head !== null && head.data === 0) {
        head = head.next;
    }
    return head;
}

// Function to add two numbers represented by linked list
function addTwoLists(num1, num2) {
    let res = null;
    let curr = null;
    let carry = 0;
    
    num1 = trimLeadingZeros(num1);
    num2 = trimLeadingZeros(num2);
    
    num1 = reverse(num1);
    num2 = reverse(num2);

    // Iterate till either num1 is not empty or num2 is
    // not empty or carry is greater than 0
    while (num1 !== null || num2 !== null || carry !== 0) {
        let sum = carry;

        // If num1 linked list is not empty, add it to sum
        if (num1 !== null) {
            sum += num1.data;
            num1 = num1.next;
        }

        // If num2 linked list is not empty, add it to sum
        if (num2 !== null) {
            sum += num2.data;
            num2 = num2.next;
        }

        // Create a new node with sum % 10 as its value
        let newNode = new Node(sum % 10);

        // Store the carry for the next nodes
        carry = Math.floor(sum / 10);

        // If this is the first node, then make this node
        // as the head of the resultant linked list
        if (res === null) {
            res = newNode;
            curr = newNode;
        } 
        else {
            // Append new node to resultant linked list
            // and move to the next node
            curr.next = newNode;
            curr = curr.next;
        }
    }

    // Reverse the resultant linked list to get the
    // required linked list
    return reverse(res);
}


//Driver Code Starts{
function printList(head) {
    let curr = head;
    let result = '';
    while (curr !== null) {
        result += curr.data + ' ';
        curr = curr.next;
    }
    console.log(result.trim());
}

// Creating first linked list: 1 -> 2 -> 3
// (represents 123)
let num1 = new Node(1);
num1.next = new Node(2);
num1.next.next = new Node(3);

// Creating second linked list: 9 -> 9 -> 9
// (represents 999)
let num2 = new Node(9);
num2.next = new Node(9);
num2.next.next = new Node(9);

let sum = addTwoLists(num1, num2);
printList(sum);

//Driver Code Ends }

Output
1 1 2 2 

Time Complexity: O(m + n), where m and n are the sizes of input linked list.
Auxiliary Space: O(max(m, n)), as we create a new linked list to store the sum of two linked lists.

[Expected Approach] By storing sum on the longer list – O(m + n) Time and O(1) Space

The idea is to iterate over both the linked list simultaneously and instead of creating a new linked list to store the result, we can store the result in the longer list itself. If we are left with some carry after traversing both the linked list, we can create a new node and append it at the end of the longer linked list.

Below is the working of above approach:


C++
//Driver Code Starts{
// C++ Program to add two number represented as
// linked list by storing sum on the longer list

#include <iostream>
using namespace std;

class Node {
  public:
    int data;
    Node *next;
    Node(int val) {
        data = val;
        next = nullptr;
    }
};
//Driver Code Ends }


// function to reverse the linked list
Node *reverse(Node *head) {
    Node *prev = nullptr, *curr = head, *next;

    while (curr != nullptr) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}

// Function to trim leading zeros in linked list
Node *trimLeadingZeros(Node* head) {
	while(head->next != nullptr && head->data == 0)
    	head = head->next;
	return head;
}

// function to find the length of linked list
int countNodes(Node* head) {
	int len = 0;
  	Node* curr = head;
  
  	while(curr != nullptr) {
    	len += 1;
      	curr = curr->next;
    }
  	return len;
}

// Function to add two numbers represented by linked list
Node *addTwoLists(Node *num1, Node *num2) {
	num1 = trimLeadingZeros(num1);
	num2 = trimLeadingZeros(num2);
  
  	// Find the length of both the linked lists
  	int len1 = countNodes(num1);
  	int len2 = countNodes(num2);
  	
  	// If num1 is smaller, swap the two linked lists by
  	// calling the function with reversed parameters
	if(len1 < len2)
      	return addTwoLists(num2, num1);

    int carry = 0;
    num1 = reverse(num1);
    num2 = reverse(num2);
  
	Node *res = num1;
  
    // Iterate till either num2 is not empty or
  	// carry is greater than 0
    while (num2 != nullptr || carry != 0) {
      
      	// Add carry to num1
        num1->data += carry;

        // If num2 linked list is not empty, add it to num1
        if (num2 != nullptr) {
            num1->data += num2->data;
            num2 = num2->next;
        }
      
        // Store the carry for the next nodes
        carry = num1->data / 10;
      	
      	// Store the remainder in num1
      	num1->data = num1->data % 10;
      	
      	// If we are at the last node of num1 but carry is 
      	// still left, then append a new node to num1
      	if(num1->next == nullptr && carry != 0)
        	num1->next = new Node(0);
      
      	num1 = num1->next;
    }

    // Reverse the resultant linked list to get the
    // required linked list
    return reverse(res);
}


//Driver Code Starts{
void printList(Node *head) {
    Node *curr = head;
    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << "
";
}

int main() {

    // Creating first linked list: 1 -> 2 -> 3
    // (represents 123)
    Node *num1 = new Node(1);
    num1->next = new Node(2);
    num1->next->next = new Node(3);

    // Creating second linked list: 9 -> 9 -> 9
    // (represents 999)
    Node *num2 = new Node(9);
    num2->next = new Node(9);
    num2->next->next = new Node(9);

    Node *sum = addTwoLists(num1, num2);
    printList(sum);

    return 0;
}
//Driver Code Ends }
C
//Driver Code Starts{
// C Program to add two number represented as
// linked list by storing sum on the longer list

#include <stdio.h>

struct Node {
    int data;
    struct Node *next;
};
//Driver Code Ends }


struct Node *createNode(int val);

// Function to reverse the linked list
struct Node *reverse(struct Node *head) {
    struct Node *prev = NULL, *curr = head, *next;

    while (curr != NULL) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}

// function to trim leading zeros in linked sort
struct Node* trimLeadingZeros(struct Node* head) {
    while (head->next != NULL && head->data == 0)
        head = head->next;
    return head;
}

// Function to find the length of linked list
int countNodes(struct Node* head) {
    int len = 0;
    struct Node* curr = head;

    while (curr != NULL) {
        len += 1;
        curr = curr->next;
    }
    return len;
}

// Function to add two numbers represented by linked list
struct Node* addTwoLists(struct Node* num1, 
                         			struct Node* num2) {
	num1 = trimLeadingZeros(num1);
	num2 = trimLeadingZeros(num2);
  
  	// Find the length of both the linked lists
    int len1 = countNodes(num1);
    int len2 = countNodes(num2);

    // If num1 is smaller, swap the two linked lists by
    // calling the function with reversed parameters
    if (len1 < len2) {
        return addTwoLists(num2, num1);
    }

    int carry = 0;
    num1 = reverse(num1);
    num2 = reverse(num2);

    struct Node* res = num1;

    // Iterate till either num2 is not empty or
    // carry is greater than 0
    while (num2 != NULL || carry != 0) {
        
      	// Add carry to num1
        num1->data += carry;

        // If num2 linked list is not empty, add it to num1
        if (num2 != NULL) {
            num1->data += num2->data;
            num2 = num2->next;
        }

        // Store the carry for the next nodes
        carry = num1->data / 10;

        // Store the remainder in num1
        num1->data = num1->data % 10;

        // If we are at the last node of num1 but carry is 
        // still left, then append a new node to num1
        if (num1->next == NULL && carry != 0)
            num1->next = createNode(0);

        num1 = num1->next;
    }

    // Reverse the resultant linked list to get the
    // required linked list
    return reverse(res);
}


//Driver Code Starts{
void printList(struct Node *head) {
    struct Node *curr = head;
    while (curr != NULL) {
        printf("%d ", curr->data);
        curr = curr->next;
    }
    printf("
");
}

struct Node *createNode(int val) {
    struct Node *node = 
      		(struct Node *)malloc(sizeof(struct Node));
    node->data = val;
    node->next = NULL;
    return node;
}

int main() {

    // Creating first linked list: 1 -> 2 -> 3
    // (represents 123)
    struct Node *num1 = createNode(1);
    num1->next = createNode(2);
    num1->next->next = createNode(3);

    // Creating second linked list: 9 -> 9 -> 9
    // (represents 999)
    struct Node *num2 = createNode(9);
    num2->next = createNode(9);
    num2->next->next = createNode(9);

    struct Node *sum = addTwoLists(num1, num2);
    printList(sum);

    return 0;
}
//Driver Code Ends }
Java
//Driver Code Starts{
// Java Program to add two number represented as
// linked list by storing sum on the longer list

class Node {
    int data;
    Node next;

    Node(int val) {
        data = val;
        next = null;
    }
}

class GfG {
//Driver Code Ends }


    // Function to reverse the linked list
    static Node reverse(Node head) {
        Node prev = null;
        Node curr = head;
        Node next;

        while (curr != null) {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    // Function to find the length of linked list
    static int countNodes(Node head) {
        int len = 0;
        Node curr = head;

        while (curr != null) {
            len += 1;
            curr = curr.next;
        }
        return len;
    }

	// function to trim leading zeros in linked list
    static Node trimLeadingZeros(Node head) {
        while (head != null && head.data == 0) {
            head = head.next;
        }
        return head;
    }
  
    // Function to add two numbers represented by linked list
    static Node addTwoLists(Node num1, Node num2) {
		num1 = trimLeadingZeros(num1);
		num2 = trimLeadingZeros(num2);
      
        // Find the length of both the linked lists
        int len1 = countNodes(num1);
        int len2 = countNodes(num2);

        // If num1 is smaller, swap the two linked lists by
        // calling the function with reversed parameters
        if (len1 < len2) {
            return addTwoLists(num2, num1);
        }

        int carry = 0;
        num1 = reverse(num1);
        num2 = reverse(num2);

        Node res = num1;

        // Iterate till either num2 is not empty or
        // carry is greater than 0
        while (num2 != null || carry != 0) {

            // Add carry to num1
            num1.data += carry;

            // If num2 linked list is not empty, add it to num1
            if (num2 != null) {
                num1.data += num2.data;
                num2 = num2.next;
            }

            // Store the carry for the next nodes
            carry = num1.data / 10;

            // Store the remainder in num1
            num1.data = num1.data % 10;

            // If we are at the last node of num1 but carry is
            // still left, then append a new node to num1
            if (num1.next == null && carry != 0) {
                num1.next = new Node(0);
            }

            num1 = num1.next;
        }

        // Reverse the resultant linked list to get the
        // required linked list
        return reverse(res);
    }


//Driver Code Starts{
    static void printList(Node head) {
        Node curr = head;
        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        
      	// Creating first linked list: 1 -> 2 -> 3
        // (represents 123)
        Node num1 = new Node(1);
        num1.next = new Node(2);
        num1.next.next = new Node(3);

        // Creating second linked list: 9 -> 9 -> 9
        // (represents 999)
        Node num2 = new Node(9);
        num2.next = new Node(9);
        num2.next.next = new Node(9);

        Node sum = addTwoLists(num1, num2);
        printList(sum);
    }
}

//Driver Code Ends }
Python
#Driver Code Starts{
# Python Program to add two number represented as
# linked list by storing sum on the longer list

class Node:
    def __init__(self, val):
        self.data = val
        self.next = None
#Driver Code Ends }


# function to reverse the linked list
def reverse(head):
    prev = None
    curr = head

    while curr is not None:
        nextNode = curr.next
        curr.next = prev
        prev = curr
        curr = nextNode

    return prev

# function to trim leading zeros in linked list
def trimLeadingZeros(head):
    while head and head.data == 0:
        head = head.next
    return head
  
# Function to find the length of linked list
def countNodes(head):
    length = 0
    curr = head

    while curr is not None:
        length += 1
        curr = curr.next

    return length

# Function to add two numbers represented by linked list
def addTwoLists(num1, num2):
    num1 = trimLeadingZeros(num1)
    num2 = trimLeadingZeros(num2)
    
    # Find the length of both the linked lists
    len1 = countNodes(num1)
    len2 = countNodes(num2)
    
    # If num1 is smaller, swap the two linked lists by 
    # calling the function with reversed parameters
    if len1 < len2:
        return addTwoLists(num2, num1)

    carry = 0
    num1 = reverse(num1)
    num2 = reverse(num2)

    res = num1

    # Iterate till either num2 is not empty or carry is greater than 0
    while num2 is not None or carry != 0:
        # Add carry to num1
        num1.data += carry

        # If num2 linked list is not empty, add it to num1
        if num2 is not None:
            num1.data += num2.data
            num2 = num2.next

        # Store the carry for the next nodes
        carry = num1.data // 10

        # Store the remainder in num1
        num1.data = num1.data % 10

        # If we are at the last node of num1 but carry is
        # still left, then append a new node to num1
        if num1.next is None and carry != 0:
            num1.next = Node(0)

        num1 = num1.next

    # Reverse the resultant linked list to get 
    # the required linked list
    return reverse(res)


#Driver Code Starts{
def printList(head):
    curr = head
    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.next
    print()

if __name__ == "__main__":
    
    # Creating first linked list: 1 -> 2 -> 3
    # (represents 123)
    num1 = Node(1)
    num1.next = Node(2)
    num1.next.next = Node(3)

    # Creating second linked list: 9 -> 9 -> 9
    # (represents 999)
    num2 = Node(9)
    num2.next = Node(9)
    num2.next.next = Node(9)

    sumList = addTwoLists(num1, num2)
    printList(sumList)

#Driver Code Ends }
C#
//Driver Code Starts{
// C# Program to add two number represented as
// linked list by storing sum on the longer list

using System;

class Node {
    public int data;
    public Node next;

    public Node(int val) {
        data = val;
        next = null;
    }
}

class GfG {
//Driver Code Ends }

    
  	// Function to reverse the linked list
    static Node Reverse(Node head) {
        Node prev = null;
        Node curr = head;
        Node next;

        while (curr != null) {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
  
	// Function to trim leading zeros
    static Node TrimLeadingZeros(Node head) {
        while (head != null && head.data == 0) {
            head = head.next;
        }
        return head;
    }

	// Function to find the length of linked list
    static int CountNodes(Node head) {
        int len = 0;
        Node curr = head;

        while (curr != null) {
            len += 1;
            curr = curr.next;
        }
        return len;
    }

    // Function to add two numbers represented by linked list
    static Node AddTwoLists(Node num1, Node num2) {
    	num1 = TrimLeadingZeros(num1);
        num2 = TrimLeadingZeros(num2);
      
        // Find the length of both the linked lists
        int len1 = CountNodes(num1);
        int len2 = CountNodes(num2);

        // If num1 is smaller, swap the two linked lists 
      	// by calling the function with reversed parameters
        if (len1 < len2)
            return AddTwoLists(num2, num1);

        int carry = 0;
        num1 = Reverse(num1);
        num2 = Reverse(num2);

        Node res = num1;

        // Iterate till either num2 is not empty 
      	// or carry is greater than 0
        while (num2 != null || carry != 0) {
          	
            // Add carry to num1
            num1.data += carry;

            // If num2 linked list is not empty, 
          	// add it to num1
            if (num2 != null) {
                num1.data += num2.data;
                num2 = num2.next;
            }

            // Store the carry for the next nodes
            carry = num1.data / 10;

            // Store the remainder in num1
            num1.data = num1.data % 10;

            // If we are at the last node of num1 but carry 
          	// is still left, then append a new node to num1
            if (num1.next == null && carry != 0)
                num1.next = new Node(0);

            num1 = num1.next;
        }

        // Reverse the resultant linked list to get the 
      	// required linked list
        return Reverse(res);
    }


//Driver Code Starts{
    static void PrintList(Node head) {
        Node curr = head;
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.next;
        }
        Console.WriteLine();
    }

    static void Main() {
        
      	// Creating first linked list: 1 -> 2 -> 3
        // (represents 123)
        Node num1 = new Node(1);
        num1.next = new Node(2);
        num1.next.next = new Node(3);

        // Creating second linked list: 9 -> 9 -> 9
        // (represents 999)
        Node num2 = new Node(9);
        num2.next = new Node(9);
        num2.next.next = new Node(9);

        Node sum = AddTwoLists(num1, num2);
        PrintList(sum);
    }
}

//Driver Code Ends }
JavaScript
//Driver Code Starts{
// JavaScript Program to add two number represented
// as linked list by storing sum on the longer list

class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
    }
}
//Driver Code Ends }


// Function to reverse the linked list
function reverse(head) {
    let prev = null;
    let curr = head;
    let next;

    while (curr !== null) {
        next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}

// function to trim leading zeros
function trimLeadingZeros(head) {
    while (head !== null && head.data === 0) {
        head = head.next;
    }
    return head;
}

// function to find the length of linked list
function countNodes(head) {
    let len = 0;
    let curr = head;

    while (curr !== null) {
        len += 1;
        curr = curr.next;
    }
    return len;
}

// Function to add two numbers represented by linked list
function addTwoLists(num1, num2) {
	num1 = trimLeadingZeros(num1);
    num2 = trimLeadingZeros(num2);

    // Find the length of both the linked lists
    const len1 = countNodes(num1);
    const len2 = countNodes(num2);

    // If num1 is smaller, swap the two linked lists by
    // calling the function with reversed parameters
    if (len1 < len2) {
        return addTwoLists(num2, num1);
    }

    let carry = 0;
    num1 = reverse(num1);
    num2 = reverse(num2);

    let res = num1;

    // Iterate till either num2 is not empty or carry is
    // greater than 0
    while (num2 !== null || carry !== 0) {
        // Add carry to num1
        num1.data += carry;

        // If num2 linked list is not empty, add it to num1
        if (num2 !== null) {
            num1.data += num2.data;
            num2 = num2.next;
        }

        // Store the carry for the next nodes
        carry = Math.floor(num1.data / 10);

        // Store the remainder in num1
        num1.data = num1.data % 10;

        // If we are at the last node of num1 but carry is
        // still left, then append a new node to num1
        if (num1.next === null && carry !== 0) {
            num1.next = new Node(0);
        }

        num1 = num1.next;
    }

    // Reverse the resultant linked list to get the required
    // linked list
    return reverse(res);
}


//Driver Code Starts{
function printList(head) {
    let curr = head;
    let result = "";
    while (curr !== null) {
        result += curr.data + " ";
        curr = curr.next;
    }
    console.log(result.trim());
}

// Creating first linked list: 1 -> 2 -> 3
// (represents 123)
let num1 = new Node(1);
num1.next = new Node(2);
num1.next.next = new Node(3);

// Creating second linked list: 9 -> 9 -> 9
// (represents 999)
let num2 = new Node(9);
num2.next = new Node(9);
num2.next.next = new Node(9);

let sum = addTwoLists(num1, num2);
printList(sum);
//Driver Code Ends }

Output
1 1 2 2 

Time Complexity: O(m + n), where m and n are the sizes of input linked list.
Auxiliary Space: O(1), as no extra linked list is used to store the sum.

[Other Approach] Using Recursion – O(m + n) Time and O(max(m, n)) Space

The idea is to use recursion to compute the sum. Recursively move to the end of the lists, calculate the sum of the last nodes (including any carry from previous additions), while backtracking add up the sums together.

For a more detailed solution and code, check this article Add two numbers represented as Linked List using Recursion.



Next Article

Similar Reads