[LeetCode] Odd Even Linked List

328. Odd Even Linked List

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for singly-linked list.
* 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:
ListNode* oddEvenList(ListNode* head) {
if(!head or !head->next) return head;
ListNode* secondTail = head->next;
ListNode* secondHead = head->next;
ListNode* headTail = head;

while(secondTail->next) {
headTail->next = secondTail->next;
headTail = headTail->next;
secondTail->next = secondTail->next->next;
headTail->next = secondHead;
if(secondTail->next)
secondTail = secondTail->next;
}
return head;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/odd-even-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.