Simple readable python solution by splitting the list


  • 0
    N

    Please read the comments.

    class Solution(object):
        def oddEvenList(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            if not head or not head.next:
                return head
            
            curr = head
            
            # My odd list
            dummyOdd  = ListNode(0)
            odd = dummyOdd
            
            # My even List
            dummyEven = ListNode(0)
            even = dummyEven
            
            i = 1
            while curr:
                if i% 2 == 1:
                    odd.next = curr
                    odd = odd.next
                else:
                    even.next = curr
                    even = even.next
                
                curr = curr.next
                i += 1
            
            # Now we have two separate lists
            odd.next = None
            even.next = None
            
            # Just join correct ends
            odd.next = dummyEven.next
            
            # Return the odd list head
            return dummyOdd.next
    

Log in to reply
 

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