问题描述:合并两个排序的链表,并将其作为新链表返回。新链表应该通过将前两个列表的节点拼接在一起来进行。
问题思路:由于两个链表均为有序,所有可以通过每个节点的大小来比较,采用递归的思路即可
链表节点定义:
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
具体算法如下:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;///先判断是否为空
ListNode listnode;
if(l1.val<l2.val)
{
listnode=l1;
listnode.next=mergeTwoLists(l1.next,l2);
}
else
{
listnode=l2;
listnode.next=mergeTwoLists(l1,l2.next);
}
return listnode;
}
if(l1==null)
return l2;
if(l2==null)
return l1;///先判断是否为空
ListNode listnode;
if(l1.val<l2.val)
{
listnode=l1;
listnode.next=mergeTwoLists(l1.next,l2);
}
else
{
listnode=l2;
listnode.next=mergeTwoLists(l1,l2.next);
}
return listnode;
}
本文介绍了一种合并两个已排序链表的方法,通过递归比对两链表节点大小,最终生成新的有序链表。
421

被折叠的 条评论
为什么被折叠?



