VOOZH about

URL: https://www.geeksforgeeks.org/dsa/add-two-numbers-represented-by-linked-list/

⇱ Add Two Numbers in a Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Add Two Numbers in a Linked List

Last Updated : 30 Aug, 2025

Given two non-negative integers represented as linked lists with heads head1 and head2, where each node contains a single digit, return a new linked list representing their sum.

Note: The input lists may contain leading zeros, but the resulting sum list must not contain any leading zeros.

Examples:

Input:

👁 aa


Explanation: Sum of 123 and 999 is 1122.

👁 bb

Input:

👁 1126

Output: 7 -> 0
Explanation: Sum of 63 and 7 is 70.

👁 2-

[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.


Output
1 -> 1 -> 2 -> 2

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

The idea is to first reverse both linked lists so that addition can be performed starting from the least significant digit. We then iterate through both lists simultaneously, adding corresponding digits along with any carry. For each sum, we create a new node and insert it at the front of the result list.

After processing all nodes, if a carry remains, we add a new node for it. Finally, the resulting list represents the sum without any leading zeros.

Illustrations:



Output
1 -> 1 -> 2 -> 2

[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.

Comment