# 328. Odd Even Linked List

## Description

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

## Solutions

• /**
* 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 {
return null;
}
ListNode b = head.next, c = b;
while (b != null && b.next != null) {
a.next = b.next;
a = a.next;
b.next = a.next;
b = b.next;
}
a.next = 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:
return nullptr;
}
ListNode *b = head->next, *c = b;
while (b && b->next) {
a->next = b->next;
a = a->next;
b->next = a->next;
b = b->next;
}
a->next = c;
}
};

• # 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]:
return None
while b and b.next:
a.next = b.next
a = a.next
b.next = a.next
b = b.next
a.next = c

• /**
* type ListNode struct {
*     Val int
*     Next *ListNode
* }
*/
return nil
}
for b != nil && b.Next != nil {
a.Next = b.Next
a = a.Next
b.Next = a.Next
b = b.Next
}
a.Next = c
}

• /**
* class ListNode {
*     val: number
*     next: ListNode | null
*     constructor(val?: number, next?: ListNode | null) {
*         this.val = (val===undefined ? 0 : val)
*         this.next = (next===undefined ? null : next)
*     }
* }
*/

function oddEvenList(head: ListNode | null): ListNode | null {
return null;
}
while (b && b.next) {
a.next = b.next;
a = a.next;
b.next = a.next;
b = b.next;
}
a.next = c;