The Odd Even Linked List is a common linked list problem typically found in FAANG-level interviews. It involves reordering a singly linked list such that all nodes at odd indices come before all nodes at even indices, preserving the relative order among odd and even nodes.
Problem Statement
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.
Note:
-
The node position/index is considered starting from 1 (not 0).
-
You must do this in O(1) space and O(n) time complexity.
Intuition
Separate the list into two:
-
One list for nodes at odd indices
-
One list for nodes at even indices
At the end, link the last node of the odd list to the head of the even list.
Algorithm
-
Edge case: If the list is empty or has one element, return the head.
-
Initialize:
-
oddpointing to the first node, -
evenpointing to the second node, -
even_headpointing to the head of the even list (used for reconnecting).
-
-
Iterate while both
odd.nextandeven.nextare not null:-
Link
odd.nexttoodd.next.next -
Move
oddone step -
Link
even.nexttoeven.next.next -
Move
evenone step
-
-
Finally, link the last
oddnode toeven_head.
Time and Space Complexity
-
Time:
O(n)— Each node is visited once. -
Space:
O(1)— Only pointers are used.
class LinkedListNode:
def __init__(self,val=0,next=None):
self.val = val
self.next = next
def create_linked_list(arr):
head = LinkedListNode(arr[0])
current = head
for k in arr[1:]:
current.next= LinkedListNode(k)
current = current.next
return head
def print_linked_list(head):
res = []
current = head
while current:
res.append(str(current.val))
current = current.next
print("=>".join(res))
def odd_even_linkked_list(head):
if not head or not head.next:
return head
odd = head
even = head.next
even_head = even
while even and even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
# now we have odd last ref and even_head first ref of even list , lets join together
odd.next = even_head
return head
k = create_linked_list([101,102,110,22,44,66,34,98])
print_linked_list(k)
print_linked_list(odd_even_linkked_list(k))