我有一个关于python中链表的快速问题。在下面显示的解决方案代码中,当我尝试合并两个已排序的链表时。我对包含的if和elif语句的条件感到困惑。例如,如果l1不是空的,l2是空的,我想将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
,因此基本上您将返回整个链接列表。如果您按如下方式遍历列表:例如,如果以下链表
lst1
和lst2
定义如下:然后您将得到最终结果:
这正是您在代码中应用的
相关问题 更多 >
编程相关推荐