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
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Add the given digit to a number stored in a linked list
- Delete a linked list using recursion
- Sum of digit of a number using recursion
- Practice questions for Linked List and Recursion
- Reverse a Doubly linked list using recursion
- Print alternate nodes of a linked list using recursion
- Remove duplicates from a sorted linked list using recursion
- Count the occurrence of digit K in a given number N using Recursion
- Traverse Linked List from middle to left-right order using recursion
- Sum and Product of nodes with value as even digit sum in Circular Linked List
- Sum and Product of all even digit sum Nodes of a Singly Linked List
- Remove all the Even Digit Sum Nodes from a Doubly Linked List
- Remove all the Even Digit Sum Nodes from a Circular Singly Linked List
- Create new linked list from two given linked list with greater element at each node
- Add one to a number represented as linked list | Set 2
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.