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
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Add the given digit to a number stored in a linked list
- Count the occurrence of digit K in a given number N using Recursion
- Sum of digit of a number using recursion
- Remove duplicates from a sorted linked list using recursion
- Reverse a Doubly linked list using recursion
- Print alternate nodes of a linked list using recursion
- Traverse Linked List from middle to left-right order using recursion
- C program to create copy of a singly Linked List using Recursion
- Delete a linked list using recursion
- Create new linked list from two given linked list with greater element at each node
- Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
- How are Java objects stored in memory?
- Practice questions for Linked List and Recursion
- Add one to a number represented as linked list | Set 2
- Add 1 to a number represented as linked list
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Merge a linked list into another linked list at alternate positions
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly linked list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.