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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
就是合并两个链表,让他们从小到大排列
时间空间上比较优秀的做法是:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 and l2:
if l1.val>l2.val:
l1,l2=l2,l1
l1.next=self.mergeTwoLists(l1.next,l2)
return l1 or l2
保持l1是连接最小结点的一个链表,通过不断交换l1和l2来实现。
本文介绍了一种高效的方法来合并两个已排序的链表,使其成为一个新的有序链表。通过递归方式,始终保持当前节点指向两个链表中较小值的一方,并进行节点拼接,最终返回合并后的链表。
1469

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



