Python solution with detailed explanation


  • 0
    G

    Solution

    Odd Even Linked List https://leetcode.com/problems/odd-even-linked-list/?tab=Description

    • Use two sentinel nodes and push odd values on one and even on others.
    class Solution(object):
        def oddEvenList(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            t_odd = odd = ListNode(-1)
            t_even = even = ListNode(-1)
            odd_ = True
            while head:
                if odd_:
                    t_odd.next = head
                    t_odd = head
                    odd_ = False
                else:
                    t_even.next = head
                    t_even = head
                    odd_ = True
                head = head.next
            t_odd.next = even.next
            t_even.next = None
            return odd.next
    

Log in to reply
 

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