描述
输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
数据范围: 0 \le n \le 10000≤n≤1000,-1000 \le 节点值 \le 1000−1000≤节点值≤1000
要求:空间复杂度 O(1)O(1),时间复杂度 O(n)O(n)
如输入{1,3,5},{2,4,6}时,合并后的链表为{1,2,3,4,5,6},所以对应的输出为{1,2,3,4,5,6}
1、迭代 139ms 15772KB
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
//定义一个含头节点的新链
ListNode newNode = new ListNode(-1);
//设置一个指针始终指向头节点
ListNode head = newNode;
//循环遍历两条链表
while (list1!=null&&list2!=null){
//比较两条链表的头节点的值
if (list1.val<list2.val){
//哪条链的头节点的值小,将该头节点拼接到新链表的后面
newNode.next = list1;
//新链表的一个指针指向下一个节点
newNode = newNode.next;
//将该链的第二个节点作为头节点,进行下一轮的比较
list1 = list1.next;
}else{
newNode.next = list2;
newNode = newNode.next;
list2 = list2.next;
}
}
//将没有遍历完的链拼接到新链的后边
if (list1!=null){
newNode.next = list1;
}else{
newNode.next = list2;
}
//将新链头节点之后的节点返回
return head.next;
}
}
2、递归 151ms 16736KB
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if (list1==null)
return list2;
if (list2==null)
return list1;
if (list1.val<list2.val){
list1.next = Merge(list1.next,list2);
return list1;
}else{
list2.next = Merge(list1,list2.next);
return list2;
}
}
}