我的思想无非就是:比较两链表的某一个值。逐渐向下遍历比较然后加到新链表中
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode listNode = new ListNode(0);
ListNode firstNode = listNode;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
listNode.next = l1;
l1 = l1.next;
} else {
listNode.next = l2;
l2 = l2.next;
}
listNode = listNode.next;
}
while (l1 != null) {
listNode.next = l1;
l1 = l1.next;
listNode = listNode.next;
}
while (l2 != null) {
listNode.next = l2;
l2 = l2.next;
listNode = listNode.next;
}
return firstNode.next;
}
不知道如何进行优化通过查资料发现可以用递归实现通过琢磨研究出递归解法
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;
}
本文探讨了如何将两个链表合并,最初的方法是通过迭代比较节点值,逐步构建新链表。进一步研究后,作者发现了利用递归解决此问题的策略,并详细介绍了递归解法。
288

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



