# Leetcode Merge Two Sorted Lists problem solution in Java

Feb 20, 2023

In the Leetcode Merge Two Sorted Lists problem solution in Java programming 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.

## Leetcode Merge Two Sorted Lists problem solution in Java programming

``````class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2)
{
if(l1 == null)
{
return l2;
}

if(l2 == null)
{
return l1;
}

if(l1.val <= l2.val)
{
l1 = l1.next;
}
else
{
l2 = l2.next;
}

while(l1 != null || l2 != null)
{
int l1Val = Integer.MAX_VALUE;
if(l1 != null)
{
l1Val = l1.val;
}

int l2Val = Integer.MAX_VALUE;
if(l2 != null)
{
l2Val = l2.val;
}

int val = 0;

if(l1Val < l2Val)
{
cur.next = new ListNode(l1Val);
cur = cur.next;
l1 = l1.next;
}
else if(l2Val < l1Val)
{
cur.next = new ListNode(l2Val);
cur = cur.next;
l2 = l2.next;
}
else
{
cur.next = new ListNode(l1Val);
cur = cur.next;
cur.next = new ListNode(l2Val);
l1 = l1.next;
}

}

}
}``````

#### By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.