Given a single-digit number k and a singly linked list whose nodes stores digits of a non-negative number, add k to the linked list.

For example, consider the linked list 9 —> 9 —> 9 —> 3 —> NULL which represents the number 9993. Adding a single-digit number 7 to it should result in the linked list 1 —> 0 —> 0 —> 0 —> 0 —> NULL which corresponds to the number 10000.

Practice this problem

The idea is to solve this problem using the basic algorithm for the addition of two numbers. But since the given list is singly linked, we can’t iterate it in the backward direction. Therefore, to facilitate the addition, we can reverse the list.

We start by adding the given single-digit number to the digit at the first node in the reversed list. If the resultant sum is a 2-digit number, update the node with a single-digit sum and move the carry to the next node. This process is repeated while there is a carry. If we reach the last node and a carry exists, add a new node at the end of the linked list with carry as the value. Finally, reverse the list again to restore the original order.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

Original linked list: 9 —> 9 —> 9 —> 9 —> 3 —> NULL
Resultant linked list: 1 —> 0 —> 0 —> 0 —> 0 —> 0 —> NULL

Java


Download  Run Code

Output:

Original linked list: 9 —> 9 —> 9 —> 9 —> 3 —> null
Resultant linked list: 1 —> 0 —> 0 —> 0 —> 0 —> 0 —> null

Python


Download  Run Code

Output:

Original linked list: 9 —> 9 —> 9 —> 9 —> 3 —> None
Resultant linked list: 1 —> 0 —> 0 —> 0 —> 0 —> 0 —> None

The time complexity of the above solution is linear, but the code performs several traversals of the linked list. We can avoid reversing the list by having recursion take care of processing the nodes in reverse order. The idea is to recursively reach the end of the linked list and pass the carry information to each parent node as the recursion unfolds.

This is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

Original linked list: 9 —> 9 —> 9 —> 9 —> 3 —> NULL
Resultant linked list: 1 —> 0 —> 0 —> 0 —> 0 —> 0 —> NULL

Java


Download  Run Code

Output:

Original linked list: 9 —> 9 —> 9 —> 9 —> 3 —> null
Resultant linked list: 1 —> 0 —> 0 —> 0 —> 0 —> 0 —> null

Python


Download  Run Code

Output:

Original linked list: 9 —> 9 —> 9 —> 9 —> 3 —> None
Resultant linked list: 1 —> 0 —> 0 —> 0 —> 0 —> 0 —> None