Introduction

This leetcode's problem is a favorite question of coding interviews. The data structure we are going to work with is Singly LinkedList. It's super fun.

Note: We are not going to use the inbuilt LinkedList class of C# because that is a doubly linked list.

The problem

Before we start the code, we first need to understand the problem clearly and make an algorithm to work with. Once you have an algorithm then it doesn’t even matter which programming language you are using.

Let's see what information do we have to work with.

Read the problem in detail from LeetCode: Add two numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

Example 1:
2 -> 4 -> 3
5 -> 6 -> 4
Result: 7 -> 0 -> 8
Explanation: 342 + 465 = 807, return 708

Example 2:
1 -> 2 -> 3
1 -> 2
Result: 2 -> 4 -> 3
Explanation: 321 + 021 = 342, return 243

Example 3:
5 -> 6 -> 7
5 -> 6 -> 7
Result: 0 -> 3 -> 5 -> 1
Explanation: 765 + 765 = 1530, return 0351

Note: These are non-empty lists so we don't need to add validations for empty lists.

Approach

Okay, so the problem says we need to reverse both lists to perform addition and then reverse the result. It may look complicated on the surface but it's really easy under the hood.

Technically we don't have to reverse anything. Since the last element in the example is the first element in the list. Neither we need to append zeros at empty spaces; instead, we can just skip that addition if the value of the node is null, as simple as that.

Algorithm (Follow example 3)

We need variables one to hold the sum, and the sum could be > 10 we need variables to hold carry and another to hold the remainder.

Note: In first iteration we have to make sure we add new node as a head to the ResultantLinkedList and from next iteration it would be ResultantLinkList.next for next it would be ResultLinkList.next.next
As you can see we have a problem here. We are not going to add (.next) for every iteration.

Instead, we can use a temporary list to pass its reference to our resultant list, and then make temporary list points to current node.

Let's bring this algorithm to life. Now please read all the comments to understand the logic.

If you run the code and debug every step, you would be executing the following statements at runtime as shown in figure 1 and 2.

Note: input is 2 -> 4 -> 3 and 5 -> 6 -> 4.

Figure 1

Figure 2

Now let’s see how code would debug for a second example.
Note: input is 1 -> 2 -> 3 and 1 -> 2

Figure 3

And that's how you do it.

Summary

Today, we learned how to create a singly linkedlist in C#, how to traverse through it. how to add new nodes into singly linkedlist and how to solve one of the most common questions of the technical interviews.

If you have any queries reach me @ Linkedin | Github