Be the first user to complete this post

  • 0
Add to List

35. Adding Two Numbers with Linked Lists

Objective: Two numbers represented by a linked listwhere each node contains single digit. The digits are stored in Forward order, means head is pointing to the last digit of the number.

Input: Two numbers represented by Linked Lists
Output: Addition of two numbers represented by a Linked List.


First Number : 1007
Second Number : 93
Addition : 1100
Two numbers represented by a linked list, Number Stored in FORWARD order


  • Get the length of both the lists.
  • If lengths are not equal, make them equal by adding nodes with value 0 in front of shorter linked list.

    Append 0 in front Shorter List

    1. Create a variable carry=0.
    2. Create a newHead = null, it will be the result linked list.
    3. Now using recursion travel in both the list till the end.
    4. So now nodes are stores in a stack
    5. Now processing the call stack, each node will pop out from the stack in reverse order
    6. Take node data from both the lists add them along with carry. Reset the carry = 0
    7. if sum is >=10 , then make carry = 1 and and do sum = sum - 10.
    8. Add the newly created node to the result linked list with the help of newHead.
    9. Repeat steps 6, 7, 8 until both the lists are over. 
    10. At the end, check if carry = 1, if yes, create a new Node with value 1 and add to result list.

    First Number : ->1->0->0->7
    Second Number : ->9->3
    Addition : ->1->1->0->0

    Also Read - Two numbers represented by a linked list, Number Stored in REVERSE order