1.题目
2.题目意思
合并两个链表,很好理解~
3.代码
解法1:
# 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:
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
思路:递归~
l1,l2为空的时候,返回另一个;都不为空,则将小的留下,大的和另一个继续合并。
每次都留下最小的那个,最后拼起来,就是啦
解法2:
# 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:
res = ListNode(None)
node = res
while l1 and l2:
if l1.val<l2.val:
node.next,l1 = l1,l1.next
else:
node.next,l2 = l2,l2.next
node = node.next
if l1:
node.next = l1
else:
node.next = l2
return res.next
思路:直接操作
先对l1和l2进行比较,之后当有一个链表空了之后,把另一个加在最后面。
不递归但是使用了额外的空间,即res
。很通俗易懂~
冲冲冲~