/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode res = new ListNode(0);
ListNode temp = res;//记得右移一位
while(l1 != null && l2 != null){
if(l1.val <= l2.val){
temp.next = new ListNode(l1.val);
temp = temp.next;
l1 = l1.next;
}
else{
temp.next = new ListNode(l2.val);
temp = temp.next;
l2 = l2.next;
}
}
while(l1 != null){
temp.next = new ListNode(l1.val);
temp = temp.next;
l1 = l1.next;
}
while(l2 != null){
temp.next = new ListNode(l2.val);
temp = temp.next;
l2 = l2.next;
}
res = res.next;
return res;
}
}
解法二(递归):
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {//递归求法
ListNode res = null;
if(l1 == null){ return l2;}//递归出口
if(l2 == null){ return l1;}//递归出口
if(l1.val <= l2.val){
res = new ListNode(l1.val);
res.next = mergeTwoLists(l1.next, l2);
}
else{
res = new ListNode(l2.val);
res.next = mergeTwoLists(l1, l2.next);
}
return res;
}
}