Python time limit exceed


  • 2
    I
    if not head:
            return head
        
        oddPointer = head
        evenPointer = head.next
        while evenPointer and evenPointer.next:
            oddPointer.next = evenPointer.next
            oddPointer = oddPointer.next
            evenPointer.next = oddPointer.next
            evenPointer = evenPointer.next
        
        oddPointer.next = head.next
        return head
    

    This exceeds time limit. However if I change it to the code below it passes. So why is it like that?

    class Solution(object):
    def oddEvenList(self, head):
        if not head:
            return head
        
        oddPointer = head
        evenPointer = head.next
        temp = head.next #this is the part where I changed
        while evenPointer and evenPointer.next:
            oddPointer.next = evenPointer.next
            oddPointer = oddPointer.next
            evenPointer.next = oddPointer.next
            evenPointer = evenPointer.next
        
        oddPointer.next = temp #this is the part where I changed
        return head

  • 0
    1

    as oddPointer = head,oddPointer.next = evenPointer.next will change head.next in fist loop.
    after then,oddPointer refers to odd.Pointer.next.that is to say ,the oddPointer updates every next of the nodes it referes to,and slips to the next...


  • 0
    X

    head.next is changed when the 3rd element is attached to the odd list.
    Your fix is explaining itself.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.