思路:一开始想到了归并算法,开头的两个相比较,谁小谁的指针往后面移动一格
要点:
1、确定退出的时候的条件
2、返回的结点前后是谁
以下是我的源代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null){
return l2;
}else if(l2==null){
return l1;
}else{
ListNode head=null;
if(l1.val<=l2.val){
head=l1;
head.next = mergeTwoLists(l1.next,l2);
}else{
head=l2;
head.next = mergeTwoLists(l1,l2.next);
}
return head;
}
}
}