原理链接:https://leetcode-cn.com/problems/odd-even-linked-list/
1、双指针
ListNode* oddEvenList(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
ListNode *p=head,*q=head->next;
ListNode *pre_p=p,*pre_q=q;
while(p->next!=NULL&&q->next!=NULL){
p->next=p->next->next;
if(p->next!=NULL) p=p->next;
q->next=q->next->next;
if(q->next!=NULL) q=q->next;
}
p->next=pre_q;
q->next=NULL;
return pre_p;
}
2、双链表
利用两个奇偶链表odd和even分别存储原链表的节点,最后将偶链表even接在奇链表odd后面,并且可以直接用odd和even替代迭代指针p,使代码更加简洁
ListNode* oddEvenList(ListNode* head) {
if(head==NULL) return head;
ListNode *odd=head,*even=head->next,*evenhead=head->next;
while(even!=NULL&&even->next!=NULL){
odd->next=even->next;
odd=odd->next;
even->next=odd->next;
even=even->next;
}
odd->next=evenhead;
return head;
}