BlackFridaySale

Join the waitlist for an extra exclusive deal

Extra savings end in
00Days
18Hrs
28Mins
25Secs
Limited spots only

110. Segregate odd and even nodes in Linked List

Given the head of a singly linked list. Group all the nodes with odd indices followed by all the nodes with even indices and return the reordered list.

Consider the 1st node to have index 1 and so on. The relative order of the elements inside the odd and even group must remain the same as the given input.

Example 1:

Input: linkedList = [1, 2, 3, 4, 5]

Output: [1, 3, 5, 2, 4]

Explanation:

The nodes with odd indices are 1, 3, 5 and the ones with even indices are 2, 4.

Example 2:

Input: linkedList = [4, 3, 2, 1]

Output: [4, 2, 3, 1]

Explanation:

The nodes with odd indices are 4, 2 and the ones with even indices are 3, 1.

Now Your Turn!

Pick the correct output for the given input

Input: linkedList = [1]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 0 <= number of nodes in the Linked List <= 105
  • 0 <= ListNode.val <= 104

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/*
Definition of singly linked list:
class ListNode{
public:
int data;
ListNode *next;
ListNode() : data(0), next(nullptr) {}
ListNode(int x) : data(x), next(nullptr) {}
ListNode(int x, ListNode *next) : data(x), next(next) {}
};
*/
 
class Solution {
public:
ListNode* oddEvenList(ListNode* &head) {
//your code goes here
}
};
Test Case

Input:

Linked List