/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* oddEvenList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
// write code here
int i = 0;
ListNode a(0), b(0);
ListNode* x = &a, *y = &b;
while (head) {
auto p = head->next;
if (i % 2 == 0) {
x = add(x, head);
} else {
y = add(y, head);
}
head->next = NULL;
head = p ;
i++;
}
if (y == &b) {
return a.next;
}
x->next = b.next;
return a.next;
}
ListNode* add(ListNode* tail, ListNode* x ) {
tail ->next = x;
return x;
}
};