Add two numbers represented by linked lists

Posted by N.K. Chauhan on Mar 31, 2024

Given two numbers represented by two linked lists, the task is to return the sum of these numbers in the form of a linked list.

Input: 9->2->7->null, 9->3->null
Output: 1->0->2->0->null

Input: 7->5->9->4->6->null, 8->4->null
Output: 8->4->null


Solutions

Method 1: Iterative

In this approach, we reverse these two lists and start from the head of the lists to add the numbers of individual nodes, just as we would in practise if we added two numbers.

Follow the steps below to solve the problem:

Reverse the two number lists.

Simulate addition at nodes one by one.

Append each node before the already calculated sum of nodes.

In the end, we will get the final answer and we can return the head node.

Complexity

The time complexity of this solution is O(max(n,m)) and space complexity is O(1).

Related


Detect a loop in a linked list (Floyd Cycle, Map, node modification)

Remove duplicates from an sorted linked list

Add 1 to a number represented as a linked list

Remove duplicates from an unsorted linked list

Delete a loop in a linked list (Floyd Cycle)

Reverse a linked list (Recursion, Iterative, Using Stack, Using Array)

Find the middle of a given linked list