python - python链表leetcode问题21合并两个有序列表
问题描述
我有一个关于 python 中的链表的快速问题。当我尝试合并两个排序的链表时,在下面显示的解决方案代码中。我对包含的 if 和 elif 语句的条件感到困惑。例如,如果 l1 不为 null 并且 l2 为 null,我想将 l1 中的其余 3 个元素添加到我的新链表中,但代码显示 l1 和 tail 没有被更新,所以它不会只添加一个3个?
我的另一个问题是关于返回 head.next。返回它会自动将head.next中的每个节点返回到null ptr吗?谢谢!
# 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()
tail = head
while l1 and l2:
if l1.val < l2.val:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next
if l1:
tail.next = l1
#why don't I update l1 and tail
elif l2:
tail.next = l2
#why don't I update l2and and tail
return head.next
#does returning head.next return every single value from head.next to null?
解决方案
好吧,您使用的是链表,因此,如果您指向特定节点并且该节点在下一个节点中有更多节点,那么您将获得所有节点。
那么这里有什么问题呢?
嗯,其实没什么。您正在返回head -> next
,所以基本上您正在返回整个链表。如果您像这样遍历列表:
merged_list = solution.mergeTwoLists(lst1, lst2)
while merged_list:
print(str(merged_list.val), end = ' -> ')
merged_list = merged_list.next
print(merged_list)
例如,如果您有以下链表lst1
并lst2
定义如下:
lst1 = ListNode(1)
lst1.next = ListNode(6)
lst1.next.next = ListNode(3) # So lst1 is basically 1 -> 6 -> 3 -> None
lst2 = ListNode(4)
lst2.next = ListNode(5)
lst2.next.next = ListNode(2) # And lst2 is basically 4 -> 5 -> 2 -> None
然后你会得到最终的结果:
1 -> 4 -> 5 -> 2 -> 6 -> 3 -> None
这正是您在代码中应用的内容。
推荐阅读
- node.js - 在 TypeScript 中使用全局变量 - Node Express
- vim - 如何在 VIM 中显示图标
- php - mysql左外连接排名
- reactjs - 如何在本机反应中将数组数据插入数据库?
- amazon-web-services - 如何从 CloudFormation 模板中访问标签?
- javascript - S3.putObject().on('httpUploadProgress', callback) 中的回调没有正确更新 React 状态数组
- reactjs - 我应该把一些操作放在功能组件的哪里
- java - 将数据提供者与 Excel 数据表一起使用
- node.js - 在 forEach (Node/Express) 中最小化 DOM 元素
- python - Pandas - 将列值转换为顺序整数