# LeetCode: Add Two Numbers Solution

Example of using dummy head technique

Use a dummy node to refer back to head

We could also understand this dummy node as a previous node of head

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}let dummy = (iter = new ListNode())2
3// begin iteration4iter.next = new ListNode(/* calculation for new node */)5iter = iter.next // new ref for pointer6// end iteration7
8return dummy.next```

## Approach

Iteration will finish when both pointers for 2 lists are null

The rest is handle sum and conditioning when

• sum is larger or equal than 10
• two lists are different in length

Remember to check the remainder at last

## Implementation

```1var addTwoNumbers = function (l1, l2) {2  let iter1 = l13  let iter2 = l24  let dummy = (iter = new ListNode())5  let remainder = 06
7  while (iter1 || iter2) {8    let val1 = iter1 ? iter1.val : 09    let val2 = iter2 ? iter2.val : 010    let val = val1 + val2 + remainder11    remainder = 012    if (val >= 10) {13      val -= 1014      remainder = 115    }16    iter.next = new ListNode(val)17    iter = iter.next18    iter1 = iter1 ? iter1.next : iter119    iter2 = iter2 ? iter2.next : iter220  }21  if (remainder === 1) {22    iter.next = new ListNode(1)23  }24
25  return dummy.next26}```

leetcode

math

## Next Post

LeetCode: Flatten a Multilevel Doubly Linked List

Aug 21, 2021

Naming variables is also important

## Previous Post

LeetCode: Merge Two Sorted Lists

Aug 19, 2021

(IMO) Not easy as categorized

Search Posts