python链表leetcode问题21合并两个排序列表

2024-03-28 22:59:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: and代码self元素l1ifvalnull
1条回答
网友
1楼 · 发布于 2024-03-28 22:59:02

好的,您使用的是一个链表,所以如果您指向一个特定的节点,并且该节点在下一个节点中有更多的节点,那么您将获得所有节点

那么这里怎么了?

其实没什么。您将返回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)

例如,如果以下链表lst1lst2定义如下:

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

这正是您在代码中应用的

相关问题 更多 >