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.
Return the head of the merged linked list.
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;
}
ListNode head = null;
// work out the head
if(l1.val <= l2.val)
{
head = l1;
l1 = l1.next;
}
else
{
head = l2;
l2 = l2.next;
}
ListNode cur = head;
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;
}
}
return head;
}
}
Also read,
- Leetcode Merge Two Sorted Lists problem solution in C++
- Leetcode Merge Two Sorted Lists problem solution in C
- Leetcode Merge Two Sorted Lists problem solution in Python
- Leetcode Merge Two Sorted Lists problem solution in C#