Add the given digit to a number stored in a linked list using recursion

• Difficulty Level : Expert
• Last Updated : 09 Jun, 2021

Given a linked list which represents an integer number where each node is a digit of the represented integer. The task is to add a given digit N to the represented integer.
Examples:

Input: LL = 9 -> 9 -> 3 -> NULL, N = 7
Output: 1 -> 0 -> 0 -> 0 -> NULL
993 + 7 = 1000
Input: LL = 2 -> 9 -> 9 -> NULL, N = 5
Output: 3 -> 0 -> 4 -> NULL

Approach: An iterative approach to solve this problem has been discussed here. In this article, a recursive approach will be discussed.
The idea is to traverse the LinkedList recursively until the last node is reached. Once the last node has been reached, add the value of N to it. After adding, if the value is more than 9 then keep the carry and set mode (digit % 10) value to the node value and add carry to the previous stack frame node, and continue until all the stack frames are cleared from the stack.
If there is a carry after all the stack frames have been cleared then create a new node with this value which will be the new head of the linked list pointing to the previous head.
Below is the implementation of the above approach:

Javascript



Output:

1 -> 0 -> 0 -> 0 -> NULL

My Personal Notes arrow_drop_up
Recommended Articles
Page :