题意:将给定的链表分成2部分,一部分是从前往后把奇数下标的链表连起来,一部分是从前往后把偶数下标的链表连起来,然后最后把偶数下标的链表连接到奇数下标链表的最后。
题解:直接模拟呗。加两个虚拟链表头会好写一点。
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
ListNode* odd = new ListNode(0);
ListNode* even = new ListNode(0);
ListNode* root1 = odd;
ListNode* root2 = even;
int num = 0;
while(head != NULL)
{
num++;
if(num % 2 == 1)
{
odd->next = head;
odd = odd->next;
}
else
{
even->next = head;
even = even->next;
}
head = head->next;
}
odd->next = root2->next;
even->next = NULL;
return root1->next;
}
};