归并的思路,就是卡在了循环没跳出来,及时注释,发现循环指针没有指向下一个 10min
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head=ListNode(0)
cur=head
while(l1!=None and l2!=None):
if(l1.val<=l2.val):
cur.next=l1
cur=cur.next # 这里可以和下面合并
l1=l1.next
else:
cur.next=l2
cur=cur.next
l2=l2.next
while(l1!=None): # cur.next = l1 or l2 可以用这个替换,python的魔法方法
cur.next=l1
cur=cur.next
l1=l1.next
while(l2!=None):
cur.next=l2
cur=cur.next
l2=l2.next
return head.next
自己写的递归版本
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# if not l1 or not l2: # Or的巧妙
# return l1 or l2
if l1==None and l2==None:
return None
if l1==None: return l2
if l2==None: return l1
if l1.val<=l2.val:
l1.next=self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next=self.mergeTwoLists(l1,l2.next)
return l2