Merge Two Sorted Lists

Sergei Golitsyn
2 min readAug 25, 2022

--

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.

Example 1:

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]

Solution:

We changed the platform. If you want to see other problems, please check my telegram channel → https://t.me/crack_code_interview

Let’s go. We have two lists. And we want to merge them. Let’s prepare a dummy head for it. With this idea in the next step, we can check the heads of the first and second lists. Is it clear? In the while loop, we can iterate over two lists. After it we must check the rest of one of the lists. And… and that is it.

public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1 == null){
return list2;
}
if (list2 == null){
return list1;
}
ListNode dummy = new ListNode();
ListNode dummyHead = dummy;

while(list1 != null && list2 != null){
if (list1.val < list2.val){
dummy.next = list1;
list1 = list1.next;
} else {
dummy.next = list2;
list2 = list2.next;
}
dummy = dummy.next;
}
while(list1 != null){
dummy.next = list1;
dummy = dummy.next;
list1 = list1.next;
}
while(list2 != null){
dummy.next = list2;
dummy = dummy.next;
list2 = list2.next;
}
return dummyHead.next;
}

--

--

Sergei Golitsyn
Sergei Golitsyn

Written by Sergei Golitsyn

7+ years of experience in building massively scalable systems (mostly using Java) both from scratch and diving into an existing codebase.

No responses yet