-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeTwoLists.java
More file actions
34 lines (29 loc) · 862 Bytes
/
Copy pathMergeTwoLists.java
File metadata and controls
34 lines (29 loc) · 862 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
25
26
27
28
29
30
31
32
33
34
package org.example;
public class MergeTwoLists {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(-999,null);
ListNode pre = dummy;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
ListNode next = list1.next;
list1.next = null;
pre.next = list1;
pre = pre.next;
list1 = next;
} else {
ListNode next = list2.next;
list2.next = null;
pre.next = list2;
pre = pre.next;
list2 = next;
}
}
if (list1 != null) {
pre.next = list1;
}
if (list2 != null) {
pre.next = list2;
}
return dummy.next;
}
}