![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0daeda3fd9af55c02a47846a53383327.png)
方法一 递归
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) {
list2.next = Merge(list1, list2.next);
return list2;
}else{
list1.next = Merge(list1.next, list2);
return list1;
}
}
}
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null) {
return list2;
}
if(list2 == null) {
return list1;
}
ListNode p1 = list1;
ListNode p2 = list2;
ListNode node = new ListNode(1);
ListNode k = node;
while(p1 != null && p2 != null) {
if(p1.val < p2.val) {
k.next = p1;
p1 = p1.next;
k = k.next;
}else{
k.next = p2;
k = k.next;
p2 = p2.next;
}
}
while(p1 != null) {
k.next = p1;
k = k.next;
p1 = p1.next;
}
while(p2 != null) {
k.next = p2;
k = k.next;
p2 = p2.next;
}
return node.next;
}
}