Add Two Numbers represented as Linked List using Recursion
Last Updated :
23 Jul, 2025
Given two numbers represented as two lists, the task is to return the sum of two lists using recursion.
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 as 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 is 1122.
Approach:
The idea is to use recursion to compute the sum. Reverse both the linked lists to start from the least significant digit. Now, traverse both the linked list recursively and in each recursive add the values of the current nodes and the carry from the previous step (initially, carry = 0). If there is a carry after the last nodes, append a new node with this carry. Finally, reverse the linked list to get the sum.
C++
// C++ code to add two linked list using recursion
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int val) {
data = val;
next = nullptr;
}
};
// Function to reverse a linked list
Node *reverse(Node *head) {
Node *prev = nullptr;
Node *curr = head;
Node *next = nullptr;
// Loop to reverse the linked list
while (curr != nullptr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
// Recursive function to add two numbers represented
// by linked lists
Node *addListRec(Node *num1, Node *num2, int &carry) {
// Base case: If both lists are empty and no carry is left
if (num1 == nullptr && num2 == nullptr && carry == 0) {
return nullptr;
}
int sum = carry;
// Add the value from the first list if it exists
if (num1 != nullptr) {
sum += num1->data;
num1 = num1->next;
}
// Add the value from the second list if it exists
if (num2 != nullptr) {
sum += num2->data;
num2 = num2->next;
}
carry = sum / 10;
Node *result = new Node(sum % 10);
// Recursively add remaining digits
result->next = addListRec(num1, num2, carry);
return result;
}
// function to trim leading zeros in linked list
Node* trimLeadingZeros(Node* head) {
while (head != nullptr && head->data == 0) {
head = head->next;
}
return head;
}
// function for adding two linked lists
Node *addTwoLists(Node *num1, Node *num2) {
num1 = trimLeadingZeros(num1);
num2 = trimLeadingZeros(num2);
// Reverse both lists to start addition from
// the least significant digit
num1 = reverse(num1);
num2 = reverse(num2);
int carry = 0;
Node *result = addListRec(num1, num2, carry);
// If there's any carry left after the addition,
// create a new node for it
if (carry != 0) {
Node *newNode = new Node(carry);
newNode->next = result;
result = newNode;
}
// Reverse the result list to restore
// the original order
return reverse(result);
}
void printList(Node *head) {
Node *curr = head;
while (curr != nullptr) {
cout << curr->data << " ";
curr = curr->next;
}
cout << "\n";
}
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;
}
C
// C code to add two linked list using recursion
#include <stdio.h>
struct Node {
int data;
struct Node *next;
};
// Function to create a new node
struct Node* createNode(int val) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = val;
newNode->next = NULL;
return newNode;
}
// Function to reverse a linked list
struct Node* reverse(struct Node* head) {
struct Node* prev = NULL;
struct Node* curr = head;
struct Node* next = NULL;
// Loop to reverse the linked list
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;
}
// Recursive function to add two numbers represented by linked lists
struct Node* addListRec(struct Node* num1,
struct Node* num2, int* carry) {
// Base case: If both lists are empty and no carry is left
if (num1 == NULL && num2 == NULL && *carry == 0) {
return NULL;
}
int sum = *carry;
// Add the value from the first list if it exists
if (num1 != NULL) {
sum += num1->data;
num1 = num1->next;
}
// Add the value from the second list if it exists
if (num2 != NULL) {
sum += num2->data;
num2 = num2->next;
}
*carry = sum / 10;
struct Node* result = createNode(sum % 10);
// Recursively add remaining digits
result->next = addListRec(num1, num2, carry);
return result;
}
// Function for adding two linked lists
struct Node* addTwoLists(struct Node* num1, struct Node* num2) {
num1 = trimLeadingZeros(num1);
num2 = trimLeadingZeros(num2);
// Reverse both lists to start addition from the
// least significant digit
num1 = reverse(num1);
num2 = reverse(num2);
int carry = 0;
struct Node* result = addListRec(num1, num2, &carry);
// If there's any carry left after the addition,
// create a new node for it
if (carry != 0) {
struct Node* newNode = createNode(carry);
newNode->next = result;
result = newNode;
}
// Reverse the result list to restore the original order
return reverse(result);
}
// Function to print a linked list
void printList(struct Node* head) {
struct Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
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;
}
Java
// Java code to add two linked list using recursion
class Node {
int data;
Node next;
Node(int val) {
data = val;
next = null;
}
}
class GfG {
// Function to reverse a linked list
static Node reverse(Node head) {
Node prev = null;
Node curr = head;
Node next = null;
// Loop to reverse the linked list
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;
}
// Recursive function to add two numbers
// represented by linked lists
static Node addListRec(Node num1, Node num2,
int[] carry) {
// Base case: If both lists are empty
// and no carry is left
if (num1 == null && num2 == null && carry[0] == 0) {
return null;
}
int sum = carry[0];
// Add the value from the first list if it exists
if (num1 != null) {
sum += num1.data;
num1 = num1.next;
}
// Add the value from the second list if it exists
if (num2 != null) {
sum += num2.data;
num2 = num2.next;
}
carry[0] = sum / 10;
Node result = new Node(sum % 10);
// Recursively add remaining digits
result.next = addListRec(num1, num2, carry);
return result;
}
// Function for adding two linked lists
static Node addTwoLists(Node num1, Node num2) {
num1 = trimLeadingZeros(num1);
num2 = trimLeadingZeros(num2);
// Reverse both lists to start addition from
// the least significant digit
num1 = reverse(num1);
num2 = reverse(num2);
// Array used to pass carry by reference
int[] carry = new int[1];
Node result = addListRec(num1, num2, carry);
// If there's any carry left after the addition,
// create a new node for it
if (carry[0] != 0) {
Node newNode = new Node(carry[0]);
newNode.next = result;
result = newNode;
}
// Reverse the list to restore the original order
return reverse(result);
}
// Function to print a linked list
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);
}
}
Python
# Python code to add two linked lists using recursion
import sys
class Node:
def __init__(self, val):
self.data = val
self.next = None
# Function to reverse a linked list
def reverse(head):
prev = None
curr = head
next = None
# Loop to reverse the linked list
while curr is not None:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
# function to trim leading zeros from linked list
def trimLeadingZeros(head):
while head and head.data == 0:
head = head.next
return head
# Recursive function to add two numbers represented
# by linked lists
def addListRec(num1, num2, carry):
# Base case: If both lists are empty and no carry is left
if num1 is None and num2 is None and carry[0] == 0:
return None
sum = carry[0]
# Add the value from the first list if it exists
if num1 is not None:
sum += num1.data
num1 = num1.next
# Add the value from the second list if it exists
if num2 is not None:
sum += num2.data
num2 = num2.next
carry[0] = sum // 10
result = Node(sum % 10)
# Recursively add remaining digits
result.next = addListRec(num1, num2, carry)
return result
# Function for adding two linked lists
def addTwoLists(num1, num2):
num1 = trimLeadingZeros(num1)
num2 = trimLeadingZeros(num2)
# Reverse both lists to start addition from the
# least significant digit
num1 = reverse(num1)
num2 = reverse(num2)
carry = [0]
result = addListRec(num1, num2, carry)
# If there's any carry left after the addition,
# create a new node for it
if carry[0] != 0:
newNode = Node(carry[0])
newNode.next = result
result = newNode
# Reverse the result list to restore the original order
return reverse(result)
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)
C#
// C# code to add two linked list using recursion
using System;
class Node {
public int data;
public Node next;
public Node(int val) {
data = val;
next = null;
}
}
// Function to reverse a linked list
class GfG {
static Node Reverse(Node head) {
Node prev = null;
Node curr = head;
Node next = null;
// Loop to reverse the linked list
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
// Function to trim leading zeros from linked list
static Node TrimLeadingZeros(Node head) {
while (head != null && head.data == 0) {
head = head.next;
}
return head;
}
// Recursive function to add two numbers represented
// by linked lists
static Node AddListRec(Node num1, Node num2,
ref int carry) {
num1 = TrimLeadingZeros(num1);
num2 = TrimLeadingZeros(num2);
// Base case: If both lists are empty and
// no carry is left
if (num1 == null && num2 == null && carry == 0) {
return null;
}
int sum = carry;
// Add the value from the first list if it exists
if (num1 != null) {
sum += num1.data;
num1 = num1.next;
}
// Add the value from the second list if it exists
if (num2 != null) {
sum += num2.data;
num2 = num2.next;
}
carry = sum / 10;
Node result = new Node(sum % 10);
// Recursively add remaining digits
result.next = AddListRec(num1, num2, ref carry);
return result;
}
// Function for adding two linked lists
static Node AddTwoLists(Node num1, Node num2) {
// Reverse both lists to start addition from
// the least significant digit
num1 = Reverse(num1);
num2 = Reverse(num2);
int carry = 0;
Node result = AddListRec(num1, num2, ref carry);
// If there's any carry left after the addition,
// create a new node for it
if (carry != 0) {
Node newNode = new Node(carry);
newNode.next = result;
result = newNode;
}
// Reverse the result list to restore
// the original order
return Reverse(result);
}
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);
}
}
JavaScript
// Javascript code to add two linked list using recursion
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
// Function to reverse a linked list
function reverse(head) {
let prev = null;
let curr = head;
let next = null;
// Loop to reverse the linked list
while (curr !== null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
function trimLeadingZeros(head) {
while (head !== null && head.data === 0) {
head = head.next;
}
return head;
}
// Recursive function to add two numbers represented
// by linked lists
function addListRec(num1, num2, carry) {
// Base case: If both lists are empty and no carry is left
if (num1 === null && num2 === null && carry === 0) {
return null;
}
let sum = carry;
// Add the value from the first list if it exists
if (num1 !== null) {
sum += num1.data;
num1 = num1.next;
}
// Add the value from the second list if it exists
if (num2 !== null) {
sum += num2.data;
num2 = num2.next;
}
carry = Math.floor(sum / 10);
let result = new Node(sum % 10);
// Recursively add remaining digits
result.next = addListRec(num1, num2, carry);
return result;
}
// Function for adding two linked lists
function addTwoLists(num1, num2) {
num1 = trimLeadingZeros(num1);
num2 = trimLeadingZeros(num2);
// Reverse both lists to start addition from
// the least significant digit
num1 = reverse(num1);
num2 = reverse(num2);
let carry = 0;
let result = addListRec(num1, num2, carry);
// If there's any carry left after the addition,
// create a new node for it
if (carry !== 0) {
let newNode = new Node(carry);
newNode.next = result;
result = newNode;
}
// Reverse the result list to restore
// the original order
return reverse(result);
}
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);
Time Complexity: O(m + n), where m and n are the sizes of given two linked lists.
Auxiliary Space: O(max(m, n))
Related article:
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