Add Two Numbers Represented as Linked List
Last Updated :
23 Jul, 2025
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 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
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
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem