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.
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 then 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:
1 -> 0 -> 0 -> 0 -> NULL
- Add the given digit to a number stored in a linked list
- Sum of digit of a number using recursion
- Delete a linked list using recursion
- Reverse a Doubly linked list using recursion
- Practice questions for Linked List and Recursion
- Remove duplicates from a sorted linked list using recursion
- Print alternate nodes of a linked list using recursion
- Traverse Linked List from middle to left-right order using recursion
- Create new linked list from two given linked list with greater element at each node
- Add 1 to a number represented as linked list
- Add one to a number represented as linked list | Set 2
- Difference between Singly linked list and Doubly linked list
- Convert singly linked list into circular linked list
- Merge a linked list into another linked list at alternate positions
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : princiraj1992