描述
输入两个递增的链表,单个链表的长度为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 ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1, ListNode list2) {
ListNode newHead = null;
ListNode tempNode = null;
ListNode endNode = null;
//1.先判断list是否存在null的情况
if (list1 == null || list2 == null) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
}
while (list1 != null && list2 != null) {
//2.取出当前循环次数中最小的结点,并赋值给temp
if (list1.val < list2.val) {
tempNode = list1;
list1 = list1.next;
} else {
tempNode = list2;
list2 = list2.next;
}
//3.将temp的节点连在新的链表newList中
if (newHead == null) {
newHead = tempNode;
newHead.next = null;
endNode = newHead;
} else {
tempNode.next = endNode.next;
endNode.next = tempNode;
endNode = endNode.next;
}
}
//4.最后某一个链表的节点已经全部比对完成了,则将后续节点直接挂在新链表的尾节点之后即可
if (list1 == null || list2 == null) {
if (list1 == null) {
endNode.next = list2;
}
if (list2 == null) {
endNode.next = list1;
}
}
return newHead;
}
}