मुख्य कंटेंट तक स्किप करें

Odd Even Linked List

KANISHKA GUPTA
EditReport

Odd Even Linked List

Description

Given a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices. Please note that the even indexed nodes should maintain their relative order. The same goes for the odd indexed nodes.

Note:

  • The head of the odd indexed list should point to the head of the even indexed list after rearranging.

Video Explanation

Approach

To solve this problem, we can use two pointers to separate the odd and even indexed nodes while maintaining their relative order. The approach involves:

  1. Initializing two pointers, odd and even, to point to the first node and the second node, respectively.
  2. Using a pointer even_head to keep track of the head of the even indexed list.
  3. Iterating through the list and rearranging the next pointers for odd and even nodes.
  4. At the end of the iteration, connecting the last odd node to the head of the even indexed list.

Solutions

class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (!head) return nullptr;
ListNode *odd = head, *even = head->next, *evenHead = even;
while (even && even->next) {
odd->next = even->next;
odd = odd->next;
even->next = odd->next;
even = even->next;
}
odd->next = evenHead;
return head;
}
};
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

💬 Discuss this page

Have a question or spot something confusing in "Odd Even Linked List"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.