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. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in O(1)
extra space complexity and O(n)
time complexity.
For example:
Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]
# 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 not head:
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
odd.next = even_head
return head
This Python code rearranges a singly linked list so that all nodes with odd indices appear before nodes with even indices. The first node is considered odd, the second is even, and so on. The relative order within the odd and even groups is preserved.
Initialization: The code starts by handling the base case where the list is empty. It then initializes pointers odd
to the head of the list, even
to the second node, and even_head
to the second node to keep track of the beginning of the even list.
Iteration: The while
loop continues as long as there are more even nodes to process (i.e., even
is not None
and even.next
is not None
). Inside the loop:
odd.next = even.next
odd
pointer moves to the next odd node: odd = odd.next
even.next = odd.next
even
pointer moves to the next even node: even = even.next
Concatenation: After the loop, the last odd node is connected to the head of the even list: odd.next = even_head
Return: The function returns the modified head of the list.
A brute-force approach might involve creating two separate lists, one for odd-indexed nodes and one for even-indexed nodes, and then concatenating them. This would require iterating through the list twice and would not satisfy the O(1) space complexity requirement.
The time complexity of this solution is O(n), where n is the number of nodes in the linked list. This is because the code iterates through the list once.
The space complexity is O(1) because the code uses a constant amount of extra space, regardless of the size of the input list. It only uses a few pointers to keep track of the nodes.
None
.