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

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:
Â
C++
// C++ implementation of the approach #include<bits/stdc++.h>using namespace std;Â
// Node class contains value// and next node referencestruct ListNode {Â Â Â Â int value;Â Â Â Â ListNode* next;};Â
// To store the carryint carry = 0;void addNewValue(ListNode*, int);Â
// Function that calls the recursive method// addNewValue to add a digit to the// number represented as the linked listListNode* addValue(ListNode* head, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int addValue){Â
  // Add the digit recursively  addNewValue(head, addValue);Â
  // If there is a carry after the addition  if (carry != 0)   {Â
    // Create a new node    ListNode* newHead = new ListNode();Â
    // Assign it with carry    newHead->value = carry;Â
    // Make it point to the head of    // the linked list    newHead->next = head;    carry = 0;Â
    // Make it the new head    return newHead;  }Â
  // If there's not carry then  // return the previous head  else  {    return head;  }}Â
// Recursive function to add a digit to the number// represented as the given linked listvoid addNewValue(ListNode* head, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int addValue){Â
  // If it is the last node in the list  if (head->next == NULL)  {Â
    // Add the digit    int val = head->value + addValue;Â
    // Find the carry if any    head->value = val % 10;    carry = val / 10;  }  else  {Â
    // Preserve the current node's value and call    // the recursive function for the next node    int val = head->value;    addNewValue(head->next, addValue);    val = val + carry;    head->value = val % 10;    carry = val / 10;  }}Â
// Utility function to print the linked listvoid printList(ListNode* node){Â Â while (node != NULL) Â Â {Â Â Â Â cout << node->value << " -> ";Â Â Â Â node = node->next;Â Â }Â Â cout<<"NULL";}Â
// Driver codeint main(){Â
  // Create the linked list 9 -> 9 -> 3 -> NULL  ListNode* head = new ListNode();  head->value = 9;  head->next = new ListNode();  head->next->value = 9;  head->next->next = new ListNode();  head->next->next->value = 3;  head->next->next->next = NULL;Â
  // Digit to be added  int n = 7;  head = addValue(head, n);Â
  printList(head);}Â
// This code is contributed by rutvik_56 |
Java
// Java implementation of the approachÂ
// Node class contains value// and next node referenceclass ListNode {Â Â Â Â int value;Â Â Â Â ListNode next;}Â
class GFG {Â
    // To store the carry    private static int carry = 0;Â
    // Function that calls the recursive method    // addNewValue to add a digit to the    // number represented as the linked list    public static ListNode addValue(ListNode head, int addValue)    {Â
        // Add the digit recursively        addNewValue(head, addValue);Â
        // If there is a carry after the addition        if (carry != 0) {Â
            // Create a new node            ListNode newHead = new ListNode();Â
            // Assign it with carry            newHead.value = carry;Â
            // Make it point to the head of            // the linked list            newHead.next = head;            carry = 0;Â
            // Make it the new head            return newHead;        }Â
        // If there's not carry then        // return the previous head        else {            return head;        }    }Â
    // Recursive function to add a digit to the number    // represented as the given linked list    private static void addNewValue(ListNode head, int addValue)    {Â
        // If it is the last node in the list        if (head.next == null) {Â
            // Add the digit            int val = head.value + addValue;Â
            // Find the carry if any            head.value = val % 10;            carry = val / 10;        }        else {Â
            // Preserve the current node's value and call            // the recursive function for the next node            int val = head.value;            addNewValue(head.next, addValue);            val = val + carry;            head.value = val % 10;            carry = val / 10;        }    }Â
    // Utility function to print the linked list    private static void printList(ListNode node)    {        while (node != null) {            System.out.print(node.value + " -> ");            node = node.next;        }        System.out.print("NULL");    }Â
    // Driver code    public static void main(String[] args)    {Â
        // Create the linked list 9 -> 9 -> 3 -> NULL        ListNode head = new ListNode();        head.value = 9;        head.next = new ListNode();        head.next.value = 9;        head.next.next = new ListNode();        head.next.next.value = 3;        head.next.next.next = null;Â
        // Digit to be added        int n = 7;        head = addValue(head, n);Â
        printList(head);    }} |
Python
# Python implementation of the approachÂ
# Node class contains value# and next node referenceclass ListNode:     def __init__(self, new_data):         self.value = new_data         self.next = NoneÂ
# To store the carrycarry = 0Â
# Function that calls the recursive method# addNewValue to add a digit to the# number represented as the linked listdef addValue(head, addValue):Â
    global carry         # Add the digit recursively    addNewValue(head, addValue)Â
    # If there is a carry after the addition    if (carry != 0) :Â
        # Create a node        newHead = ListNode(0)Â
        # Assign it with carry        newHead.value = carryÂ
        # Make it point to the head of        # the linked list        newHead.next = head        carry = 0Â
        # Make it the head        return newHead             # If there's not carry then    # return the previous head    else :        return head     # Recursive function to add a digit to the number# represented as the given linked listdef addNewValue(head,addValue):         global carryÂ
    # If it is the last node in the list    if (head.next == None) :Â
        # Add the digit        val = head.value + addValueÂ
        # Find the carry if any        head.value = val % 10        carry = int(val / 10)         else :Â
        # Preserve the current node's value and call        # the recursive function for the next node        val = head.value        addNewValue(head.next, addValue)        val = val + carry        head.value = val % 10        carry = int(val / 10)         # Utility function to print the linked listdef printList(node):         while (node != None) :        print(node.value ,end= " -> ")        node = node.next             print("None")     # Driver codeÂ
# Create the linked list 9 -> 9 -> 3 -> Nonehead = ListNode(0)head.value = 9head.next = ListNode(0)head.next.value = 9head.next.next = ListNode(0)head.next.next.value = 3head.next.next.next = NoneÂ
# Digit to be addedn = 7head = addValue(head, n)Â
printList(head)Â
# This code is contributed by Arnab Kundu |
C#
// C# implementation of the approach using System;Â
// Node class contains value// and next node referencepublic class ListNode {Â Â Â Â public int value;Â Â Â Â public ListNode next;}Â
class GFG{Â
    // To store the carry    private static int carry = 0;Â
    // Function that calls the recursive method    // addNewValue to add a digit to the    // number represented as the linked list    public static ListNode addValue(ListNode head,                                      int addValue)    {Â
        // Add the digit recursively        addNewValue(head, addValue);Â
        // If there is a carry after the addition        if (carry != 0)         {Â
            // Create a new node            ListNode newHead = new ListNode();Â
            // Assign it with carry            newHead.value = carry;Â
            // Make it point to the head of            // the linked list            newHead.next = head;            carry = 0;Â
            // Make it the new head            return newHead;        }Â
        // If there's not carry then        // return the previous head        else        {            return head;        }    }Â
    // Recursive function to add a digit to the number    // represented as the given linked list    private static void addNewValue(ListNode head,                                      int addValue)    {Â
        // If it is the last node in the list        if (head.next == null)        {Â
            // Add the digit            int val = head.value + addValue;Â
            // Find the carry if any            head.value = val % 10;            carry = val / 10;        }        else        {Â
            // Preserve the current node's value and call            // the recursive function for the next node            int val = head.value;            addNewValue(head.next, addValue);            val = val + carry;            head.value = val % 10;            carry = val / 10;        }    }Â
    // Utility function to print the linked list    private static void printList(ListNode node)    {        while (node != null)         {            Console.Write(node.value + " -> ");            node = node.next;        }        Console.Write("NULL");    }Â
    // Driver code    public static void Main(String[] args)    {Â
        // Create the linked list 9 -> 9 -> 3 -> NULL        ListNode head = new ListNode();        head.value = 9;        head.next = new ListNode();        head.next.value = 9;        head.next.next = new ListNode();        head.next.next.value = 3;        head.next.next.next = null;Â
        // Digit to be added        int n = 7;        head = addValue(head, n);Â
        printList(head);    }}Â
// This code is contributed by PrinciRaj1992 |
Javascript
<script>Â
// JavaScript implementation of the approachÂ
// Node class contains value// and next node referenceclass ListNode {Â Â Â Â Â Â Â Â constructor() {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â this.value = 0;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â this.next = null;Â Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â // To store the carrylet carry = 0;Â
// Function that calls the recursive method// addNewValue to add a digit to the// number represented as the linked listfunction addValue( head, addValue){Â
    // Add the digit recursively    addNewValue(head, addValue);Â
    // If there is a carry after the addition    if (carry != 0) {Â
        // Create a new node        var newHead = new ListNode();Â
        // Assign it with carry        newHead.value = carry;Â
        // Make it point to the head of        // the linked list        newHead.next = head;        carry = 0;Â
        // Make it the new head        return newHead;        }Â
    // If there's not carry then    // return the previous head    else {        return head;    }}Â
// Recursive function to add a digit to the number// represented as the given linked listfunction addNewValue( head, addValue){Â
    // If it is the last node in the list    if (head.next == null) {Â
        // Add the digit        let val = head.value + addValue;Â
        // Find the carry if any        head.value = val % 10;        carry = Math.floor(val / 10);    }    else {Â
        // Preserve the current node's value and call        // the recursive function for the next node        let val = head.value;        addNewValue(head.next, addValue);        val = val + carry;        head.value = val % 10;        carry = Math.floor(val / 10);        }    }Â
// Utility function to print the linked listfunction printList( node){Â Â Â Â while (node != null) {Â Â Â Â Â Â Â Â document.write(node.value + " -> ");Â Â Â Â Â Â Â Â node = node.next;Â Â Â Â }Â Â Â Â document.write("NULL");}Â
// Driver CodeÂ
// Create the linked list 9 -> 9 -> 3 -> NULLvar head = new ListNode();head.value = 9;head.next = new ListNode();head.next.value = 9;head.next.next = new ListNode();head.next.next.value = 3;head.next.next.next = null;Â
// Digit to be addedlet n = 7;head = addValue(head, n);Â
printList(head);Â Â Â Â Â </script> |
1 -> 0 -> 0 -> 0 -> NULL
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



