21. Merge Two Sorted Lists
Solution
With the concept of merge sort, we check the list to find which node is less than one another and put it into list.
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode curr = head;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
curr.next = l1;
l1 = l1.next;
}else{
curr.next = l2;
l2 = l2.next;
}
curr = curr.next;
}
curr.next = l1 == null ? l2 : l1;
return head.next;
}
Last updated
Was this helpful?