public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null) {
return list2;
}
if(list2 == null) {
return list1;
}
ListNode head = null;
//上下跳即可
if(list1.val < list2.val) {
head = list1;
head.next = Merge(list1.next, list2);
} else {
head = list2;
head.next = Merge(list1, list2.next);
}
return head;
}
}
合并两个排序的数组
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] array1 = {1, 2, 5, 8, 9, 11, 13};
int[] array2 = {4, 6, 7, 10, 12, 15};
int[] result = Merge(array1, array2);
System.out.println(Arrays.toString(result));
}
public static int[] Merge(int [] arr1, int[] arr2) {
int[] result = new int[arr1.length + arr2.length];
int i = 0, j = 0, index = 0;
while (i < arr1.length && j <arr2.length) {
if(arr1[i] < arr2[j]) {
result[index++] = arr1[i++];
} else {
result[index++] = arr2[j++];
}
}
if (i == arr1.length && j != arr2.length) {
result[index++] = arr2[j++];
return result;
}
if (i != arr1.length && j == arr2.length) {
result[index++] = arr1[i++];
return result;
}
return result;
}
}