1、题目描述
输入两个递增的链表,单个链表的长度为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},转换过程如下图所示:
2、 算法分析
分为两种情况:
先创建一个结果集的链表。
ListNode node = new ListNode(0);
并且定义当前结点current指向node
current往后走,node始终指向结果链表的开头。
①当两个链表都不为Null的时候,比较两个链表的值,将较小的值附加在node的下一个结点。
②当其中的一个链表为null的时候,直接将后面的结点复制到node下即可。
3、代码实现
/*
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 node = new ListNode(0);
ListNode current = node;
while(list1 != null && list2 != null){
if(list1.val >= list2.val){
current.next = list2;
list2 = list2.next;
}else{
current.next = list1;
list1 = list1.next;
}
current = current.next;
}
if(list1 != null){
current.next = list1;
}
if(list2 != null){
current.next = list2;
}
return node.next;
}
}