一.问题描述
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
二.解题思路
就是把两个有序的列表合成一个有序的链表:
1.非递归方法:
如果l1和l2都为空,返回空链表。
创建一个空头head,然后再用一个变量记录这个头。
否则,开始迭代:
<1.判断l1和l2都不空并且l1的值小于l2或者l1不空l2空
此时下一个插入点是l1的当前节点。
插入完将更新l1和head至他们下一个节点。
<2.不满足1,则为插入2
<3.剪枝操作,若l1或者l2某一个是空,可以返回了
2.递归法
和上面差不多。
判断当前节点哪个小,然后让当前节点的next指向子递归。
用递归就是要弄清递归的返回条件和分割条件。
分割来说,对当前递归来说,之后的节点已经被组成了一个有序的链表,我只需决定我当前从l1和l2中选哪一个节点做我的当前节点,然后让其指向下一次递归返回的结果。具体看一下代码把。
更多leetcode算法题解法: 专栏 leetcode算法从零到结束
三.源码
1.迭代
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#58
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 and not l2:return
head=ListNode(0)
root=head
while l1 or l2:
if l1 and l2 and l1.val <l2.val or l1 and not l2:
head.next=l1
l1=l1.next
else:
head.next=l2
l2=l2.next
if not l1 or not l2:break
head=head.next
return root.next
2.递归
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#58
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 and not l2: return None
if not l1:return l2
if not l2:return l1
head=ListNode(0)
if l1.val<l2.val:
head=l1
head.next=self.mergeTwoLists(l1.next,l2)
else:
head=l2
head.next=self.mergeTwoLists(l1,l2.next)
return head