数据结构—线性结构—链表:(合并两个排序链表)
一、题目:将两个排序链表合并为一个新的排序链表
样例:给出 1->3->8->11->15->null
,2->null
, 返回 1->2->3->8->11->15->null
。
二、分析:
需要考虑的点:
1、某个链表为空、或者都为空;
2、空间复杂度,在原地链接结点
三、代码:
/**
*Definition for ListNode
*/
public class ListNode{
int val;
ListNode next;
ListNode(int x){
val = x;
next = null;
}
}
public class Solution{
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
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;
}
}