登录
  • #刷题
  • #leetcode

21‌‌‍‍‌‍‍‌‍‍‌‍‍‌‍‍‍‌‍‌‌‌‌‍‌‌‌‍‌‌‍‍. Merge two sorted lists 合并有序链表这题的一个小问题

熊云天
455
10
Leetcode 第21题 Merge two sorted lists 合并有序链表,我写的是迭代解法:

# 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:

if not l1 or not l2:

return l1 or l2

l = ListNode(0)

tmp = l.next

while l1 and l2:

if l1.val <= l2.val:

tmp = l1

l1 = l1.next

else:

tmp = l2

l2 = l2.next

tmp = tmp.next

tmp = l1 or l2

return l.next

但是!上述答案提交返回的结果为空list,肯定是不对的。下面的标准答案,对next指针的处理有不同,和上面答案不同的地方用粗体标注了出来:

参考的标准答案:

# 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:

if not l1 or not l2:

return l1 or l2

l = ListNode(0)

tmp = l

while l1 and l2:

if l1.val <= l2.val:

tmp.next = l1

l1 = l1.next

else:

tmp.next = l2

l2 = l2.next

tmp = tmp.next

tmp.next = l1 or l2

return l.next

请问为什么我的写法不对呢?感觉逻辑上和标准答案没区别,就是某些地方对next指针的处理不一样。

小白刚开始刷题,希望各位不吝赐教,提前谢谢了
10条回复
热度排序

发表回复