21. 合并两个有序链表
这个题没有什么难的地方,是链表的基本操作,只要熟悉链表的常见写法就可以做出来。
用两个指针p1,p2指向两个链表,一个指针pre指向合并后的链表的最后的元素,比较两个指针指向的元素的大小,让pre.next = 大的那个
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1==None:return l2
if l2==None:return l1
if l1.val<l2.val:
now = l1
l1 = l1.next
else:
now = l2
l2 = l2.next
renode = now
while(l1!=None and l2!=None):
if l1.val<l2.val:
now.next = l1
now=now.next
l1 = l1.next
else:
now.next = l2
now=now.next
l2 = l2.next
if l1==None:
now.next = l2
else:
now.next = l1
return renode
优化:这里我们首先还要判断pre首先应该在哪,比较麻烦。不如直接设置一个头结点head,最后返回head.next即可
`class Solution:
def mergeTwoLists(self, l1, l2):
prehead = ListNode(-1)
prev = prehead
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
# 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
prev.next = l1 if l1 is not None else l2
return prehead.next
`
省略了很多麻烦的步骤。
递归
下面我们使用递归来解决这个问题。
`class Solution:
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
`
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。