题目:输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
数据范围: 0 ≤ n ≤ 1000,-1000 ≤ 节点值 ≤ 1000
要求:空间复杂度 O(1),时间复杂度 O(n)
如输入{1,3,5},{2,4,6}时,合并后的链表为{1,2,3,4,5,6},所以对应的输出为{1,2,3,4,5,6},转换过程如下图所示:
或输入{-1,2,4},{1,3,4}时,合并后的链表为{-1,1,2,3,4,4},所以对应的输出为{-1,1,2,3,4,4},转换过程如下图所示:
示例1
输入:{1,3,5},{2,4,6}
返回值:{1,2,3,4,5,6}
示例2
输入:{},{}
返回值:{}
示例3
输入:{-1,2,4},{1,3,4}
返回值:{-1,1,2,3,4,4}
解法一:
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null) {
return list2;
}
if(list2 == null) {
return list1;
}
ListNode newNode = null;
if(list1.val <= list2.val) {
newNode = list1;
list1 = list1.next;
} else {
newNode = list2;
list2 = list2.next;
}
ListNode prev = newNode;
while (list1 != null & list2 != null) {
if(list1.val <= list2.val) {
prev.next = list1;
prev = prev.next;
list1 = list1.next;
} else {
prev.next = list2;
prev = prev.next;
list2 = list2.next;
}
}
if(list1 != null) {
prev.next = list1;
}
if(list2 != null) {
prev.next = list2;
}
return newNode;
}
}
解法二:
import java.util.ArrayList;
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
ArrayList arr1 = new ArrayList();
while (list1 == null & list2 == null) {
return null;
}
while (list1 != null & list2 != null) {
if (list1.val <= list2.val) {
arr1.add(list1.val);
list1 = list1.next;
} else {
arr1.add(list2.val);
list2 = list2.next;
}
}
while (list1 != null) {
arr1.add(list1.val);
list1 = list1.next;
}
while (list2 != null) {
arr1.add(list2.val);
list2 = list2.next;
}
Integer[] arr2 = new Integer[arr1.size()];
arr1.toArray(arr2);
for(int j = 0; j < arr2.length; j ++) {
System.out.println(arr2[j]);
}
ListNode newNode = new ListNode(arr2[0]);
ListNode prev = newNode;
for(int i = 1; i < arr2.length; i ++) {
ListNode node = new ListNode(arr2[i]);
newNode.next = node;
newNode = newNode.next;
}
return prev;
}
}