Odd Even Linked List

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on. The relative order inside both the even and odd groups should remain as it was in the input. Solve the problem in O(1) extra space complexity and O(n) time complexity.

Constraints

  • The number of nodes in the linked list is in the range [0, 10^4].
  • -10^6 <= Node.val <= 10^6
Saving… · 8 lines
# 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]:
Console

Click Run to execute sample tests.