定义两个头节点(奇数位头节点、偶数位头节点),遇到奇数位就加载奇数链表下,遇到偶数位就加载偶数链表
/**
* 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) return head;
ListNode* a=(ListNode*)malloc(sizeof(ListNode));
ListNode* b=(ListNode*)malloc(sizeof(ListNode));
ListNode* cur=head,*aa=a,*bb=b,*t=NULL;
int i=1;
while(cur!=NULL){
t=cur->next;
if(i%2==1){
aa->next=cur;
aa=cur;
aa->next=NULL;
}else{
bb->next=cur;
bb=cur;
bb->next=NULL;
}
cur=t;
i++;
}
aa->next=b->next;
return a->next;
}
};