题目介绍
递归法
如果l1,l2刚开始就是空的,直接返回另一个链表即可,否则,进行递归,先判断 l1 和 l2 哪一个的头元素更小,然后递归地决定下一个添加到结果里的值,直到有一个为空。
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
else if (l2 == null) {
return l1;
}
else if (l1.val < l2.val) {
l1.next = MergeTwoLists(l1.next, l2);
return l1;
}
else {
l2.next = MergeTwoLists(l1, l2.next);
return l2;
}
}
}
迭代法
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
ListNode result=new ListNode(0);
ListNode l3=result;
while(l1!=null&&l2!=null)
{
if(l1.val<l2.val)
{
l3.next=l1;
l1=l1.next;
}
else
{
l3.next=l2;
l2=l2.next;
}
l3=l3.next;
}
if(l1==null)
l3.next=l2;
if(l2==null)
l3.next=l1;
return result.next;
}
}