328. Odd Even Linked List

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head ||!head->next) return head;
ListNode *odd= new ListNode (-1), *a = odd, *even = new ListNode(-1), *b = even;
ListNode * p = head;
while(p ){
odd->next = p;
odd=odd->next;
p=p->next;
if(p){
even->next = p;
p=p->next;
even = even->next;
}
}
even->next = nullptr;
odd->next = b->next;
return a->next;
}
};

analysis

  • time complexity O(n)
  • space complexity O(1)