I came up with a solution based on turns.
I think this solution is less error-prone and easier.
The test passes, but please let me know how it looks.
Thanks!
shared_ptr<ListNode<int>> EvenOddMerge(const shared_ptr<ListNode<int>>& L) {
if(L == nullptr) {
return L;
}
shared_ptr<ListNode<int>> even_dummy(new ListNode<int>),
odd_dummy(new ListNode<int>);
array<shared_ptr<ListNode<int>>, 2> tails;
tails[0] = even_dummy, tails[1] = odd_dummy;
int turn = 0;
auto iter = L;
while (iter) {
tails[turn]->next = iter;
tails[turn] = tails[turn]->next;
turn ^= 1;
iter = iter->next;
}
if (turn == 1) { //last node was an even node
tails[1]->next = nullptr;
}
tails[0]->next = odd_dummy->next;
return even_dummy->next;
}