-
Notifications
You must be signed in to change notification settings - Fork 0
Example: Merge two sorted lists
Roberto Fronteddu edited this page Jul 27, 2024
·
1 revision
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into 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.
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
var n = list1;
var m = list2;
if (n == null) {
return m;
}
if (m == null) {
return n;
}
ListNode newList = null;
while (n != null || m != null) {
if (n == null) {
newList.next = m;
newList = newList.next;
m = m.next;
continue;
}
if (m == null) {
newList.next = n;
newList = newList.next;
n = n.next;
continue;
}
ListNode newNode;
if (n.val < m.val) {
newNode = n;
n = n.next;
} else {
newNode = m;
m = m.next;
}
if (newList == null) {
newList = newNode;
} else {
newList.next = newNode;
newList = newList.next;
}
}
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
return list1.val < list2.val ? list1 : list2;
}
}