思路:遍历链表生成奇链表和偶链表,然后拼接两个链表生成新的链表。
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
ListNode* pre = new ListNode(-1);
ListNode* pre_temp = pre;
ListNode* end = new ListNode(-1);
ListNode* end_temp = end;
int i = 1;//用来判断奇偶
while(head){
if(i%2==1){
pre_temp->next = head;
pre_temp = pre_temp->next;
}else{
end_temp->next = head;
end_temp = end_temp->next;
}
i++;
head = head->next;
}
end_temp->next = nullptr;
pre_temp->next = end->next;
return pre->next;
}
};