注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
if (l1.val <= l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l2.next, l1);
return l2;
}
}
}
本文介绍了一种合并两个已排序链表的方法,并提供了一个简洁的Java实现方案。该方法通过递归方式比较两个链表的节点值,将较小的节点连接到结果链表中,直至遍历完两个链表。
1469

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



