Merge Two Sorted Lists — Leetcode

Oshi Raghav
2 min readApr 13, 2023

--

Problem Statement:
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]
Input: list1 = [], list2 = [0]
Output: [0]
Input: list1 = [], list2 = []
Output: []

Explanation:

Code:

class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode temp_node = new ListNode();
ListNode current_node = temp_node;

while( l1 != null && l2 != null){
if(l1.val < l2.val){
current_node.next = l1;
l1= l1.next;
}
else{
current_node.next = l2;
l2= l2.next;
}
current_node = current_node.next;
}
if(l1 != null){
current_node.next = l1;
l1= l1.next;
}
if(l2 != null){
current_node.next = l2;
l2= l2.next;
}
return temp_node.next;
}
}

Thank you
Oshi Raghav

--

--

Oshi Raghav
Oshi Raghav

Written by Oshi Raghav

3rd year CSE student | GDSC Lead | Front-end developer

No responses yet