# LeetCode: Merge Two Sorted Lists Solution

(IMO) Not easy as categorized

## Approach

Keep iteratate two pointers, one for each list

Append smaller node to the dummy node on each iteration

## Implementation (iterative)

```.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;}var mergeTwoLists = function (l1, l2) {2  let dummy = (iter = new ListNode())3
4  while (l1 && l2) {5    if (l1.val < l2.val) {6      iter.next = l17      l1 = l1.next8    } else {9      iter.next = l210      l2 = l2.next11    }12    iter = iter.next13  }14
15  // because the above loop stop when one of the list pointers is null16  // so this line is to make sure we don't miss the last pointer17  iter.next = l1 || l218
19  return dummy.next20}```

## Implementation (recursive)

`1var mergeTwoLists = function (l1, l2) {2  if (!l1) return l23  if (!l2) return l14  if (l1.val < l2.val) {5    l1.next = mergeTwoLists(l1.next, l2)6    return l17  } else {8    l2.next = mergeTwoLists(l1, l2.next)9    return l210  }11}`

## (Bonus) Implementation (break and rebuild)

Convert to arrays

Concat and sort

```1var mergeTwoLists = function (l1, l2) {2  const llistToArray = llist => {3    let iter = llist4    const res = []5    while (iter) {6      res.push(iter.val)7      iter = iter.next8    }9    return res10  }11  const arrayToLlist = arr => {12    let dummy = (iter = new ListNode())13    arr.forEach(el => {14      const node = new ListNode(el)15      iter.next = node16      iter = iter.next17    })18    return dummy.next19  }20
21  return arrayToLlist(22    [...llistToArray(l1), ...llistToArray(l2)].sort((a, b) => a - b)23  )24}```

leetcode

## Next Post

Aug 20, 2021

Example of using dummy head technique