题目描述
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
第一次错误
# 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:
a=ListNode(1)
while l1 and l2:
if l1.val<=l2.val:
a.next=l1
l1=l1.next
else:
a.next=l2
l2=l2.next
if l1:
a.next=l1
else:
a.next=l2
return a
后来发现a指针一直停留在第一位,没有向下移动,所以只保留了初始化的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:
a=ListNode(1)
while l1 and l2:
if l1.val<=l2.val:
a.next=l1
l1=l1.next
else:
a.next=l2
l2=l2.next
a=a.next
if l1:
a.next=l1
else:
a.next=l2
return a
后来发现是因为我return的是a这个指针,而a在执行过程中一直往后移动,所以只返回了最后一个值加上最后加上的元素。应该想办法返回整个链表第一个元素的地址。
第三次错误
# 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:
a=ListNode(1)
b=a
while l1 and l2:
if l1.val<=l2.val:
b.next=l1
l1=l1.next
else:
b.next=l2
l2=l2.next
b=b.next
if l1:
b.next=l1
else:
b.next=l2
return a
考虑到多了一个1,应该是我设置的链表里面的第一个元素。在返回时应该用a.next来去掉那一个元素
正解
# 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:
a=ListNode(1)
b=a
while l1 and l2:
if l1.val<=l2.val:
b.next=l1
l1=l1.next
else:
b.next=l2
l2=l2.next
b=b.next
if l1:
b.next=l1
else:
b.next=l2
return a.next
对链表认识还是不够好
执行用时 :36 ms, 在所有 Python3 提交中击败了86.20%的用户
内存消耗 :13.4 MB, 在所有 Python3 提交中击败了17.11%的用户
递归法
看了官方的思路。一般很难想到递归
# 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
elif 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
执行用时 :40 ms, 在所有 Python3 提交中击败了68.12%的用户
内存消耗 :13.6 MB, 在所有 Python3 提交中击败了16.49%的用户