Daily LeetCode Challenge (Day 12)#21. Merge Two Sorted Lists

Felix Ivance Runye
2 min readJul 3, 2023
Photo by Joshua Sortino on Unsplash

Difficulty | Easy

Challenge

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: list1 = [], list2 = []
Output: []

Example 3:

Input: list1 = [], list2 = [0]
Output: [0]

Thought Process & Pseudo Code

  • Check linked lists Reference in another article with a different challenge
  • Get all elements from the list and add them to a single array
  • sort the array
  • loop through the elements and add them to a linked list
  • return the list

Solution in php

/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val = 0, $next = null) {
* $this->val = $val;
* $this->next = $next;
* }
* }
*/
class Solution {

/**
* @param ListNode $list1
* @param ListNode $list2
* @return ListNode
*/
function mergeTwoLists($list1, $list2) {
// get elements and add them to an array
$num1 = [];

while($list1){
array_push($num1,$list1->val );
$list1 = $list1->next;
}

while($list2){
array_push($num1,$list2->val );
$list2 = $list2->next;
}

// sort the array
sort($num1);
$list = null;
// add to a new listnode
$i=0;
for($i = count($num1)-1; $i>=0; $i--){
$list = new ListNode($num1[$i], $list );
}
return $list;
}
}

Solution Javascript

/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeTwoLists = function(list1, list2) {
let numbers= [];

while(list1){
numbers.push(list1.val);
list1 = list1.next;
}

while(list2){
numbers.push(list2.val);
list2 = list2.next;
}
//custom sort function to sort smallest to largest
let sortedNumbers = numbers.sort(function(a,b) { return a - b; });

let list = null;

for(let i= sortedNumbers.length-1; i >=0; i--){
list = new ListNode(sortedNumbers[i], list);
}
return list;

};

PS: The challenges get easier with time 😁

--

--

Felix Ivance Runye

I am a Software Engineer, and an Adventurer, who is passionate about cycling, biking, and reading. Always on the lookout for new challenges.