[Python] Why do I need to assign to `output.next` in this solution for Merge Sorted Linked...

Discussão em 'Python' iniciado por Stack, Dezembro 21, 2024.

  1. Stack

    Stack Membro Participativo

    The correct solution below for the Merge Two Sorted Linked Lists Leetcode problem fails when you remove the .next in lines 12, 15, 24:

    output.next = list1 becomes output = list1

    output.next = list2 becomes output = list2

    return head.next becomes return head

    Correct solution


    # 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, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
    head = output = ListNode()

    while list1 and list2:
    if list1.val < list2.val:
    output.next = list1
    list1 = list1.next
    else:
    output.next = list2
    list2 = list2.next
    output = output.next

    if list1 and output:
    output.next = list1
    elif list2 and output:
    output.next = list2

    return head.next


    I expected it to work exactly the same. When I print output within the loop, it prints the remaining tail of the current list that's lesser than.

    Continue reading...

Compartilhe esta Página