描述:输入两个递增的链表,单个链表的长度为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},转换过程如下图所示:
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode p,q,next1,next2,r;
p=list1;
q=list2;
if(list1==null){
return list2;
}
if(list2==null){
return list1;
}
if(list1.val<list2.val){
r=list1;
p=p.next;
}else{
r=list2;
q=q.next;
}
while(p!=null&&q!=null){
if(p.val<q.val){
r.next=p;
r=p;
p=p.next;
}else{
r.next=q;
r=q;
q=q.next;
}
}
if(p!=null){
r.next=p;
}else{
r.next=q;
}
if(list1.val<list2.val){
return list1;
}else{
return list2;
}
}
}