Odd Even Linked List
To achieve the required grouping of nodes with odd and even indices together, you can create two pointers: one pointing to the current odd-indexed node and the other to the current even-indexed node. Then, you iterate through the linked list, rearranging the links to group the odd and even nodes together.
Here’s the step-by-step solution to implement the oddEvenList
method:
- Initialize Pointers: Create two pointers
odd
andeven
initialized to the first and second nodes respectively. - Iterate through the List: Traverse the linked list, updating the
next
pointers of the odd and even nodes to skip the next node in the sequence. - Link Odd and Even Lists: At the end of the traversal, link the last node of the odd list to the first node of the even list.
- Return Head: Return the head of the linked list, which remains unchanged.
Here is the implementation:
|
|
Key Takeaways
- This solution fulfills the requirement of using (O(1)) extra space complexity, as it rearranges the existing links without creating additional data structures.
- The time complexity is (O(n)), as it iterates through the linked list once.
- The solution ensures that the relative order inside both the even and odd groups remains as it was in the input, as required.
=begin
v v 1->2->3->4->5->NULL ^ ^ 4 pointers + 1 pointer for keeping track of the second node that will become the start of the even nodes Complicated it more than necessary
I misunderstood T:O(N) O(N) + O(N)
Two Pointers
- odd (creates the odd list)
- even (creates the even list)
1->2->3->4->5->NULL ^ odd.next = odd.next.next 1->3 even.next = even.next.next 2->4
odd.next = even_head
end of the odd list needs to point to the beginning of the even list do this after the loop
odd: ->5 even First time traversal, hop from 1, 3, 5 Odd pointer starts from odd Even pointer starts from 1 tail pointer to keep track
terminating condition
- odd.next is null when I reach the end of the list (odd number of elements)
- even.next is null when I reach the end of the list (even number of elements)
|
|
|
|