我有一个关于 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?