# Odd Even Linked List – Leetcode Solution

In this post, we are going to solve the 328. Odd Even Linked List problem of Leetcode. This problem 328. Odd Even Linked List is a Leetcode easy level problem. Let’s see code, 328. Odd Even Linked List – Leetcode Solution.

## Problem

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.

### Example 1 :

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

### Example 2 :

``````
Output: [2,3,6,7,1,5,4]
``````

### Constraints

• The number of nodes in the linked list is in the range `[0, 104]`.
• `-106 <= Node.val <= 106`

Now, let’s see the code of 328. Odd Even Linked List – Leetcode Solution.

# Odd Even Linked List – Leetcode Solution

### 328. Odd Even Linked List – Solution in Java

```/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {

ListNode odd = currOdd;
ListNode even = currEven;

while(currEven != null && currEven.next != null){
currOdd.next = currOdd.next.next;
currOdd = currOdd.next;
currEven.next = currEven.next.next;
currEven = currEven.next;
}

currOdd.next = even;
return odd;
}
}```

### 328. Odd Even Linked List – Solution in C++

```/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode() : val(0), next(nullptr) {}
*     ListNode(int x) : val(x), next(nullptr) {}
*     ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:

while(odd->next != NULL && even->next != NULL){
odd->next = even->next;
odd = even->next;
even->next = odd->next;
even = odd->next;
}
}
};```

### 328. Odd Even Linked List– Solution in Python

```# 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]:
root1=ListNode(0)
root2=ListNode(0)
root=root2
t=root1
count=0
if count%2!=0:
root1=root1.next
else:
root2=root2.next
count+=1
root2.next=t.next
return root.next
```

Note: This problem 328. Odd Even Linked List is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.