# Javascript Coding Interview Questions

## The easy approach to ‘Linked List’ and ‘Adding two numbers’ questions

Given two numbers represented by two lists, which will return the sum of the list. The sum list is a list representation of the addition of two input numbers.

Input:
`List1: 9->4->2// represents number 249 `
`List2: 6->5->4 // represents number 456`

`Output: Resultant list: 5->0->7 // represents number 705 Explanation: 249 + 456 = 705`

## Solution

Let’s learn how to create Node, Node will have its own data and pointer which will point to the next Node.

`// singly-linked list. class Node {    constructor(val) {      this.data = val;      this.next = null;    }}`

now, Let’s create two linked list, example -

`// creating first list, actual number is 249head1 = new Node(9);head1.next = new Node(4);head1.next.next = new Node(2);// creating second list, actual number is 456head2 = new Node(6);head2.next = new Node(5);head2.next.next = new Node(4);`

Let’s pass head1 and head2 to `addTwoLists` method,

`sumofTwoNumberList = addTwoLists(head1, head2);`

The final solution will look like this,

• We have reversed linked lists and we need to iterate over each of them and add values from both lists to each other. As a result, we need to return a new linked list with the sum of the values.
• We need to carry out value. Because you have to have a single digit value in every node. If you add 5 + 5 the result is 10, so you live 0 in the recent node and move 1 to the next node. And in the next node, you will add 1 to the sum.
`let carryOver = 0let addTwoLists = function(head1, head2) {    if(!head1 && !head2 && carryOver === 0) {        return null;     }        let headValue1 = head1 ? head1.data : 0;    let headValue2 = head2 ? head2.data : 0;        let sum = carryOver + headValue1 + headValue2;    carryOver = Math.floor(sum/10);    let nextHead1 = head1 ? head1.next : null;    let nextHead2 = head2 ? head2.next : null;            return {        value: sum % 10,        next: addTwoLists(nextHead1, nextHead2)    };};addTwoLists(head1, head2)`

Output,