Two Pointers Python Solution


  • 0

    The idea is to use two pointers to track the end of even and odd lists. The whole process is kind of like an unzipping process. It might be similar to some of the methods mentioned in other threads, but I thought this might be a little easier to read.

    def oddEvenList(self, head):
        if not head: return None
        if not head.next: return head
        odd = head
        even = head.next
        evenhead = even
        
        while even and even.next and even.next.next:
            odd.next = even.next
            odd = odd.next
            even.next = odd.next
            even = even.next
            
        if even.next:
            odd.next = even.next
            odd = odd.next
            even.next = None
            
        odd.next = evenhead
        return head
    

    Note that evenhead stores the beginning point of even list. It can also be head.next


Log in to reply
 

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