写这个博客,不仅是为了给别人看,更是做一个记录,以下代码python3实现,参考一些答案
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
#第一种常规方法
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(0)
curr = head
while l1 is not None and l2 is not None:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l2 if l1==None else l1
return head.next
#第二种迭代方法
class Solution:
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
这个题目其实之前做过很多次,每次都是参考别人的运行完,就万事大吉了,下次遇到这个的题还是不会写