Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Hide Buttons

Add two numbers represented by a linked list, Numbers are Stored in REVERSE order

We have similar post – Two numbers represented by a linked list, Number Stored in FORWARD order

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

Input: Two numbers represented by Linked Lists

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

Example:

First Number in REVERSE order: 5957
Second Number in REVERSE order : 59
Addition in REVERSE order : 0967
Actual Result in FORWARD ORDER : 9670

Approach:

  1. Take a variable int carry =0.
  2. Initialize Node newHead = null; and Node curr = null.
  3. newHead will be the starting node of our result linked list and curr node will the reference to the current node on which we are working in our result linked list.
  4. Navigate Both the lists simultaneously taking one node at a time.
  5. Add the data of nodes and carry , say you call this as total.
  6. Check if total >=10, if yes put carry =1 and total=total-10.
  7. create a new node with value total, say you call it as Node ‘n’.
  8. check if newHead is null, if yes then and assign ‘n’ to newHead. Now our starting node of result linked list is fixed.
  9. if newHead is not null then add ‘n’ to the result linked list with the help of newHead and curr.
  10. Now repeat steps 4 to 9 till any one of the list gets over( considering both the list has different length, if both list has the same length then both lists gets over at the same time, you will not need step 11).
  11. Now navigate the list ( whichever is remaining) and add it to the result list. (take care of the carry, see Example). You can avoid this step by making sure that both the list has the same length adding 0 at the end of the shorter list , to see the similar implementation click here.
  12. At the End check the carry, if it is not 0, create a new node with value 1 and add it to the result linked list.

Example:

First Number : 179
Second Number : 86
Add two numbers represented by a linked list, Number Stored in REVERSE order

Add two numbers represented by a linked list, Number Stored in REVERSE order

Complete Code:


Output:

First Number in REVERSE order: 5957
Second Number in REVERSE order : 59
Addition in REVERSE order : 0967
Actual Result in FORWARD ORDER : 9670

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: