Recursively traverse the linked list, reaching the last node first. This ensures that the least significant digit is processed before others.
Add 1 to the value of the last node and compute any carry resulting from this addition.
While backtracking, update each node's value based on the carry propagated from the subsequent node.
After traversing, if the carry is not equals to 0, create new node with the data as carry andinsert it at head.
Output
2 0 0 0
Time Complexity: O(n), where n is the number of nodes in the linked list. Auxiliary Space: O(n)
Iterative - O(n) Time and O(1) Space:
Reverse given linked list. For example, 1-> 9-> 9 -> 9 is converted to 9-> 9 -> 9 ->1.
Start traversing linked list from leftmost node and add 1 to it. If there is a carry, move to the next node. Keep moving to the next node while there is a carry. This gives us 0->0->0->2
After traversing, if the carry is not equals to 0, create new node with the data as carry andinsert it at head. In this case, the carry is 0.
Reverse modified linked list and return head. This gives us 2->0->0->0
Output
2 0 0 0
Time Complexity: O(n), where n is the number of nodes in the linked list. Auxiliary Space: O(1), As constant extra space is used.