 # 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

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.
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
```

(Click on the image to enlarge it)

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
```

### 2 thoughts on “Add two numbers represented by a linked list, Numbers are Stored in REVERSE order”

1. Found two bugs in the above code.
1) in first while loop if carry becomes 1 no where carry is set to ‘0’ again. once carry value is ‘1’ it will always be ‘1’.
should be like this..

if (total >= 10) {
carry = total / 10;
total %= 10;
} else
carry = 0;

2) If the input given as “1” && “99” above program results 010..it should be 001

in while (l1!=null) && while(l2!=null) loop creating new node with the total. If the total is 10 then it will create node with 10. Inside need to have condition as below.

if (total >= 10) {
carry = total / 10;
total %= 10;
} else
carry = 0;