328. Odd Even Linked List

Medium

Problem:

Reorganize the linked list so that the odd nodes come before the even nodes. Solve it with space complexity O(1)O(1) and time complexity O(n)O(n).

Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]

https://leetcode.com/problems/odd-even-linked-list/

Solution:

The variables such as odd, even, and even_head are always used consistently, regardless of the size of n,n, thus the space complexity also satisfies the constraint of O(1)O(1).

Tip: The processing for odd and even can be bundled together into one multiple assignment.

# 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]:
        if head is None:
            return None
        
        odd = head
        even = head.next
        even_head = head.next

        while even and even.next:
            odd.next, even.next = odd.next.next, even.next.next
            odd, even = odd.next, even.next
        
        odd.next = even_head
        return head
If there are no constraints on space and time:

If you convert the linked list into a list and utilize various functions provided by Python lists such as slicing, you can solve it more easily, intuitively, and quickly.

Last updated