输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
数据范围: 0≤�≤10000≤n≤1000,−1000≤节点值≤1000−1000≤节点值≤1000
要求:空间复杂度 �(1)O(1),时间复杂度 �(�)O(n)
如输入{1,3,5},{2,4,6}时,合并后的链表为{1,2,3,4,5,6},所以对应的输出为{1,2,3,4,5,6}
示例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 (list2 == null) {
return list1;
} else if (list1 == null) {
return list2;
}
ListNode mergeList = new ListNode(-1);
ListNode gurad = mergeList;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
mergeList.next = list1;
list1 = list1.next;
mergeList = mergeList.next;
} else {
mergeList.next = list2;
list2 = list2.next;
mergeList = mergeList.next;
}
}
if (list2 == null) {
mergeList.next = list1;
} else if (list1 == null) {
mergeList.next = list2;
}
return gurad.next;
}
}