解法:选择其中一个链表加入虚表头,在该原列表里插入另一个列表
时间负责度O(n)
空间复杂度O(1)
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1==null&&list2==null)
return null;
if(list1==null)
return list2;
if(list2==null)
return list1;
ListNode h = new ListNode(-1);
h.next = list1;
ListNode p_pre = h;
ListNode p = h.next;
ListNode q = list2;
while(p!=null&&q!=null){
if(p.val<q.val){
p_pre = p;
p = p.next;
}else{
ListNode t = q.next;
q.next = p_pre.next;
p_pre.next = q;
//要记得更换p
p_pre = q;
q = t;
}
}
if(p==null){
p_pre.next=q;
}
return h.next;
}
}