[Python] Need help finding deadloop in this linked list python code! (Leetcode 328)

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to solve Leetcode Q328:

    Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

    Here is my code:

    # Definition for singly-linked list.
    # class ListNode:
    # def __init__(self, val=0, next=None):
    # self.val = val
    # self.next = next
    class Solution:
    def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
    node = head
    odd = True
    lastOdd = None
    while node:
    temp = node.next
    if node.next:
    if node.next.next:
    node.next = node.next.next
    else:
    if odd:
    lastOdd = node
    else:
    if odd:
    lastOdd = node
    break
    node = temp
    odd = not(odd)
    lastOdd.next = head.next
    return head


    When tested with [1,2,3,4,5], I would either run out of time or memory, so I'm assuming there is a deadloop somewhere. But I've combed through the logic a couple of times and couldn't find it!

    I'm relatively sure that the deadloop happens with the following part as deleting this part will allow the program to finish:

    else:
    if odd:
    lastOdd = node


    This is actually already the second version of my code, originally it was:

    else:
    if odd:
    node.next = head.next


    But why does it deadloop? I have used temp to store the next node in the original chain separately already, and the loop should just stop after node reaches the end of the chain!

    Any help is appreciated! I'm just starting to learn about linked lists so it might be a really dumb question.

    Continue reading...

Compartilhe esta Página