-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathSolution.java
More file actions
24 lines (20 loc) · 732 Bytes
/
Copy pathSolution.java
File metadata and controls
24 lines (20 loc) · 732 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
current.next = list1;
list1 = list1.next;
} else {
current.next = list2;
list2 = list2.next;
}
current = current.next;
}
// Attach the remaining nodes from the non-exhausted list
if (list1 != null) current.next = list1;
else current.next = list2;
return dummy.next; // Return the head of the merged list
}
}