/**
* 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) {
// write code here
ListNode* var=new ListNode(1);//偶数节点虚拟头节点
ListNode* var1=new ListNode(1);//奇数节点虚拟头节点
ListNode* pre=var;
ListNode* pre1=var1;
ListNode* cur=head;
int i=1;//标记当前节点位置
while(cur)
{
if(i%2==0){pre->next=cur;pre=pre->next;}
else {pre1->next=cur;pre1=pre1->next;}
cur=cur->next;i++;
}
pre1->next=var->next;//奇数链表连接偶数链表
pre->next=nullptr;
head=var1->next;
delete var;delete var1;
return head;
}
};
定义两个虚拟头节点,分别来连接偶数和奇数节点,最后把两个链表连接即可。

京公网安备 11010502036488号